我有一个如下所示的数组
array:2 [▼
0 => array:2 [▼
"id" => 0
"item_code" => "abc001"
]
1 => array:2 [▼
"id" => 1
"item_code" => "abc002"
]
]
当id = 0时,如何将其拆分为新数组?
// $newArr to store id = 0
0 => array:2 [▼
"id" => 0
"item_code" => "abc001"
]
// $oldArr to store id != 0
1 => array:2 [▼
"id" => 1
"item_code" => "abc002"
]
我想将每个id = 0存储到$ newArr并将id!= 0存储到$ oldArr中。
答案 0 :(得分:3)
您可以使用收集方法。首先,包装你的数组:
$collection = collect($array);
1。使用where()
:
@foreach ($collection->where('id', 0) as $item)
{{ $item['item_code'] }}
@endforeach
@foreach ($collection->where('id', '!=', 0) as $item)
{{ $item['item_code'] }}
@endforeach
2。使用partition()
:
list($idIsZero, $idIsNotZero) = $collection->partition(function ($i) {
return $i['id'] === 0;
});
在大多数情况下,您不需要将集合转换回数组,但如果需要,请在集合上使用->toArray()
。
答案 1 :(得分:2)
<强> INPUT 强>
$array = array(
array("id" => 0,"item_code" => "abc001"),
array("id" => 1,"item_code" => "abc002")
);
<强>解强>
$oldArray = array();
$newArray = array();
foreach($array as $row){
if($row['id']==0)$oldArray[] = $row;
else $newArray[] = $row;
}
echo "New<pre>";print_r($newArray);echo "</pre>";
echo "Old<pre>";print_r($oldArray);echo "</pre>";
<强>输出强>
New
Array
(
[0] => Array
(
[id] => 1
[item_code] => abc002
)
)
Old
Array
(
[0] => Array
(
[id] => 0
[item_code] => abc001
)
)
答案 2 :(得分:1)