我有这个数组
Array
(
[0] => Array
(
[id] => book
[name] => Array
(
[0] => author
[1] => title
[2] => genre
[3] => price
[4] => publish_date
[5] => description
)
)
[1] => Array
(
[id] => book
[name] => Array
(
[0] => author
[1] => title
[2] => genre
[3] => price
[4] => publish_date
[5] => description
)
)
)
Array
(
[0] => Array
(
[id] => library
[name] => Array
(
[0] => room
[1] => room
)
)
[1] => Array
(
[id] => library
[name] => Array
(
[0] => book
[1] => book
[2] => book
[3] => book
)
)
)
我希望我的输出看起来像
Array
(
[0] => Array
(
[id] => library
[name] => Array
(
[0] => room
[1] => room
)
(
[0] => book
[1] => book
[2] => book
[3] => book
)
)
)
Array
(
[0] => Array
(
[id] => book
[name] => Array
(
[0] => author
[1] => title
[2] => genre
[3] => price
[4] => publish_date
[5] => description
)
)
}
我正在尝试这样做,比较所有ID和名称如果它具有相同的 ID 如此唯一,则所有值 [name] 一起获取如果它具有相同的名称和相同的ID则唯一非常感谢我正在尝试这样做,但它只返回唯一 id,并且有警告:未定义的索引:名称
if (is_array($servico))
{
foreach($servico as $data)
{
$result[$data['id']][] = ($data['name']);
}
}
在
添加新元素之前,您需要检查新元素是否已在数组中,以便只获得唯一元素。为了防止出现关于未定义索引的警告,如果元素尚不存在,则需要对其进行初始化。
foreach ($servico as $data) {
if (!isset($result[$data['id']])) {
$result[$data['id']] = array();
}
if (!in_array($data['name'], $result[$data['id']])) {
$result[$data['id']][] = $data['name'];
}
}