我有一个这样的数组:
Array(
[0] => Array(
[id] => 1
[name] => name1
[table] => warehouse)
[1] => Array(
[id] => 2
[name] => name2
[table] => warehouse)
[2] => Array(
[id] => 3
[name] => name1
[table] => kitchen)
[3] => Array(
[id] => 4
[name] => name5
[table] => kitchen)
)
我希望得到这个结果。 array_unique不起作用,因为只有一个值相同,我想只用名称排序。 id和表格可以相同。
Array(
[0] => Array(
[id] => 1
[name] => name1
[table] => warehouse)
[1] => Array(
[id] => 2
[name] => name2
[table] => warehouse)
[3] => Array(
[id] => 4
[name] => name5
[table] => kitchen))
答案 0 :(得分:3)
试试这个
$data = Array(
[0] => Array(
[id] => 1
[name] => name1
[table] => warehouse)
[1] => Array(
[id] => 2
[name] => name2
[table] => warehouse)
[2] => Array(
[id] => 3
[name] => name1
[table] => kitchen)
[3] => Array(
[id] => 4
[name] => name5
[table] => kitchen)
);
$record = array();
$name = array();
foreach($data as $key=>$value){
if(!in_array($value['name'], $name)){
$name[] = $value['name'];
$record[$key] = $value;
}
}
print_r($record);
答案 1 :(得分:2)
如果您不使用vanilla-PHP,可以使用ouzo-goodies库执行此操作:
$uniqueByName = Arrays::uniqueBy($array, 'name');
答案 2 :(得分:1)
这个怎么样?
它只有唯一的记录
如果有几个类似的记录,最后一个将占优势。
$new = [];
foreach($array as $a) $new[$a['name']] = $a;
print_r($new);
如果您只希望以相同的方式占优势,您可能必须首先array_reverse()
数组。
答案 3 :(得分:0)
有2个foreach声明,你可以这样做..
让我们说些什么......
$arr1 = array("shayan","ali","shayan","maziar","pezhman","ali");
$arr2 = array();
foreach($arr1 as $element1)
{
foreach($arr1 as $element2)
{
if ($element1 != $element2 && !in_array($element1,$arr2))
{
array_push($arr2,$element1);
}
}
}
print_r($arr2);
希望它有所帮助< 3
答案 4 :(得分:0)
您可以使用与ArrayHelper
框架捆绑在一起的Yii
。
$array = array_values(ArrayHelper::index($array, 'name'));