Reputation: 867
I have an array as shown below
array:2 [▼
0 => array:2 [▼
"id" => 0
"item_code" => "abc001"
]
1 => array:2 [▼
"id" => 1
"item_code" => "abc002"
]
]
How can i split it into new array when 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"
]
I want to store every id = 0 into $newArr and id !=0 into $oldArr.
Upvotes: 3
Views: 4444
Reputation: 9853
If your $array is a collection then try where()-
$new_array = $array->where('id','=',0);
$old_array = $array->where('id','!=',0);
If its a array then make it a collection first using collect()-
$array = collect($array);
Upvotes: 1
Reputation: 163798
You can use collection methods. First, wrap your array:
$collection = collect($array);
1. Use the where()
:
@foreach ($collection->where('id', 0) as $item)
{{ $item['item_code'] }}
@endforeach
@foreach ($collection->where('id', '!=', 0) as $item)
{{ $item['item_code'] }}
@endforeach
2. Use the partition()
:
list($idIsZero, $idIsNotZero) = $collection->partition(function ($i) {
return $i['id'] === 0;
});
In the most cases you don't need to transform collection back to array, but if you need to, use ->toArray()
on a collection.
Upvotes: 4
Reputation: 2327
INPUT
$array = array(
array("id" => 0,"item_code" => "abc001"),
array("id" => 1,"item_code" => "abc002")
);
SOLUTION
$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>";
OUTPUT
New
Array
(
[0] => Array
(
[id] => 1
[item_code] => abc002
)
)
Old
Array
(
[0] => Array
(
[id] => 0
[item_code] => abc001
)
)
Upvotes: 2