3

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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
        )

)

Comments

1

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);

5 Comments

Please explain you code ... I got error from your code.. Please tell me how it is working...?
we can query through collection object with where() method that is available with laravel. Have a look at this link please laravel.com/docs/5.5/collections#method-where
Okay... This is laravel project... I was running it in core php.. No Issue.. Thanks...
Why is it show me Trying to get property of non-object error when i loop in blade? Is it return null value then caused the error?
try dd($single_object) and see in your loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.