I have got the following array:
$raw = [
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'new'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'new'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'new'
],
];
I need to filter through this array, preferably using filter_array
to keep the code cleaner, I need to filter based on the path
property. So I would end up with:
$filtered = [
'used' => [
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'used'
]
],
'new' => [
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'new'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'new'
],
[
'prop1' => 'somevalue',
'prop2' => 'anothervalue',
'path' => 'new'
]
]
];
Your code lacks commas, so it's syntactically invalid. See the updated corrected code in the demo below. You just need this simple code:
<?php
$filtered = array();
foreach ($raw as $item) {
$filtered[$item["path"]][] = $item;
}
Output
Array
(
[used] => Array
(
[0] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => used
)
[1] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => used
)
[2] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => used
)
[3] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => used
)
[4] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => used
)
)
[new] => Array
(
[0] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => new
)
[1] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => new
)
[2] => Array
(
[prop1] => somevalue
[prop2] => anothervalue
[path] => new
)
)
)
Demo: https://eval.in/1047516