如果 addon_id 键不存在,如何从多维数组中删除
How to delete from a multidimensional array if addon_id key is not present
到这里为止,我已经自己解决了所有与此有关的问题。到目前为止,我已经做到了能够正确保存数据的程度。我唯一的问题是,如何删除 addon_id 不存在的数组?
我想从数组中删除最后两个“addon_price”。
[
{"addon_id":"7","addon_price":"12"},
{"addon_id":"8","addon_price":"45"},
{"addon_id":"9","addon_price":"66"},
{"addon_price":null}, <- remove
{"addon_price":null} <- remove
]
这是我的代码
$p = ItemsAddon::where('item_id', $request->item_id)->pluck('addon_id');
if($request->addon_id) {
$addons = [
'addon_id' => $request->addon_id,
'addon_price' => $request->addon_price
];
$values = [];
foreach($addons as $key => $addon) {
foreach($addon as $subkey => $subvalue) {
$values[$subkey][$key] = $subvalue;
}
}
foreach($values as $vkey => $value) {
$item_addon = new ItemsAddon;
if(!$p->contains($value['addon_id'])) {
$item_addon->item_id = $request->item_id;
$item_addon->addon_id = $value['addon_id'];
$item_addon->addon_price = $value['addon_price'];
$item_addon->save();
} else {
$item_addon->where(
[
'item_id' => $request->item_id,
'addon_id' => $value['addon_id'],
])->update([
'addon_id' => $value['addon_id'],
'addon_price' => $value['addon_price'],
]);
}
}
}
如果你有这样的数组
$a = [
["addon_id" => "7", "addon_price" => "12"],
["addon_id" => "8", "addon_price" => "45"],
["addon_id" => "9", "addon_price" => "66"],
["addon_price" => null],
["addon_price" => null]
];
那么你可以这样过滤空值:
$b = collect($a)->filter(function ($r) {
return isset($r["addon_id"]);
})->toArray();
到这里为止,我已经自己解决了所有与此有关的问题。到目前为止,我已经做到了能够正确保存数据的程度。我唯一的问题是,如何删除 addon_id 不存在的数组?
我想从数组中删除最后两个“addon_price”。
[
{"addon_id":"7","addon_price":"12"},
{"addon_id":"8","addon_price":"45"},
{"addon_id":"9","addon_price":"66"},
{"addon_price":null}, <- remove
{"addon_price":null} <- remove
]
这是我的代码
$p = ItemsAddon::where('item_id', $request->item_id)->pluck('addon_id');
if($request->addon_id) {
$addons = [
'addon_id' => $request->addon_id,
'addon_price' => $request->addon_price
];
$values = [];
foreach($addons as $key => $addon) {
foreach($addon as $subkey => $subvalue) {
$values[$subkey][$key] = $subvalue;
}
}
foreach($values as $vkey => $value) {
$item_addon = new ItemsAddon;
if(!$p->contains($value['addon_id'])) {
$item_addon->item_id = $request->item_id;
$item_addon->addon_id = $value['addon_id'];
$item_addon->addon_price = $value['addon_price'];
$item_addon->save();
} else {
$item_addon->where(
[
'item_id' => $request->item_id,
'addon_id' => $value['addon_id'],
])->update([
'addon_id' => $value['addon_id'],
'addon_price' => $value['addon_price'],
]);
}
}
}
如果你有这样的数组
$a = [
["addon_id" => "7", "addon_price" => "12"],
["addon_id" => "8", "addon_price" => "45"],
["addon_id" => "9", "addon_price" => "66"],
["addon_price" => null],
["addon_price" => null]
];
那么你可以这样过滤空值:
$b = collect($a)->filter(function ($r) {
return isset($r["addon_id"]);
})->toArray();