如何处理,如果有相同的名字,只需在数组中添加id

时间:2018-10-26 21:25:08

标签: php multidimensional-array

我有这个数组:

"disciplinesFilter": [
                {
                    "id": "4745",
                    "name": "test"
                },
                {
                    "id": "4843",
                    "name": "test"
                }
            ]

需要以下处理:

  • 如果名称已经存在,只需在数组中添加ID,如下所示:

    “ disciplinesFilter”:[             {                 “ID”: [                    {                      4843,                      4745                     }                 ]                 “名称”:“测试”             }         ]

  • 如果不使用名称和ID创建另一行。

    “ disciplinesFilter”:[{“ id”:[{4843,4745}]“ name”:“ test”},{“ id”:[{1111}]“ name”:“ test2”}]

这是我要创建的代码:

$name = '';
$disciplinesFilter = array();

foreach ($disciplines as $key => $discipline) {

$discipline['name'] = substr($discipline['name'], 0, strpos($discipline['name'], "|"));

if( $discipline['name'] == $name ) {

$disciplinesFilter[$key - 1]['id'] = $discipline['id'] ;

} else {

$name = $discipline['name'];

$disciplinesFilter[] = array(
'id' => $discipline['id'],
'name' => $discipline['name']
);

}
}

你能帮我吗?

谢谢。

0 个答案:

没有答案