我有一个类似的数组
Array
(
[0] => Array
(
[id] => BA
[name] => British Airways
)
[1] => Array
(
[id] => BA
[name] => British Airways
)
[2] => Array
(
[id] => LA
[name] => Lanchile
)
[3] => Array
(
[id] => LA
[name] => Lanchile
)
[4] => Array
(
[id] => BA
[name] => British Airways
)
[5] => Array
(
[id] => BA
[name] => British Airways
)
)
我想要
Array
(
[0] => Array
(
[id] => BA
[name] => British Airways
)
[1] => Array
(
[id] => LA
[name] => Lanchile
)
)
但在使用arrayunique函数后,我所拥有的只是
Array
(
[0] => Array
(
[id] => BA
[name] => British Airways
)
)
我做错了什么?
array_unique(my_array, SORT_REGULAR)
如评论中所要求。:(
如上所述,array_unique不支持多维数组,但您可以迭代数据并构建自己的
<?php
$airlines = array(
array('id' => 'BA', 'name' => 'British Airways'),
array('id' => 'LA', 'name' => 'Lanchile'),
array('id' => 'BA', 'name' => 'British Airways'),
array('id' => 'LA', 'name' => 'Lanchile'),
array('id' => 'BA', 'name' => 'British Airways'),
array('id' => 'LA', 'name' => 'Lanchile'),
);
$tmp = array();
foreach ($airlines as $item) {
if (!in_array($item['id'], $tmp)) {
$unique[] = $item;
$tmp[] = $item['id'];
}
}
var_dump($unique); // $unqiue will have your desired results in it var_dump was just for testing
array_unique is not intended to work on multi dimensional arrays.
你需要循环阵列
array_唯一
$airlines = array(
array('id' => 'BA', 'name' => 'British Airways'),
array('id' => 'LA', 'name' => 'Lanchile'),
array('id' => 'BA', 'name' => 'British Airways'),
array('id' => 'LA', 'name' => 'Lanchile'),
array('id' => 'BA', 'name' => 'British Airways'),
array('id' => 'LA', 'name' => 'Lanchile'),
);
$unique = array_map(
'unserialize',
array_unique(
array_map(
'serialize',
$airlines
)
)
);
var_dump($unique);