我有以下数组:
$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'
],
];
Run Code Online (Sandbox Code Playgroud)
我需要过滤这个数组,最好使用filter_array保持代码更清洁,我需要根据path属性进行过滤.所以我最终会:
$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'
]
]
];
Run Code Online (Sandbox Code Playgroud)
您的代码缺少逗号,因此它在语法上无效.请参阅下面演示中更新的更正代码.你只需要这个简单的代码:
<?php
$filtered = array();
foreach ($raw as $item) {
$filtered[$item["path"]][] = $item;
}
Run Code Online (Sandbox Code Playgroud)
产量
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
)
)
)
Run Code Online (Sandbox Code Playgroud)
演示: https ://eval.in/1047516
| 归档时间: |
|
| 查看次数: |
29 次 |
| 最近记录: |