我有一个像这样填充的数组:
array_push($comboUserPosts,
array(
'link'=> get_permalink(),
'dates'=> $value,
'title'=> get_the_title()
)
);
然后,当我完成所有循环时,我会这样做:
array_unique($comboUserPosts);
但它仍然给我重复。如果我这样做:
echo '<pre>' . var_export($comboUserPosts, true) . '</pre>';
这就是我得到的:
array (
0 =>
array (
'link' => 'https://example.com/test/test-values-users/',
'dates' => '1920',
'title' => 'test values users',
),
1 =>
array (
'link' => 'https://example.com/test/test-values-users/',
'dates' => ' 1954',
'title' => 'test values users',
),
2 =>
array (
'link' => 'https://example.com/test/provo-filter/',
'dates' => '1600',
'title' => 'provo filter',
),
3 =>
array (
'link' => 'https://example.com/test/provo-filter/',
'dates' => '1450',
'title' => 'provo filter',
),
4 =>
array (
'link' => 'https://example.com/test/provo-filter/',
'dates' => '1330',
'title' => 'provo filter',
),
)
但是通过查看,我只有2个独特的链接和标题,我应该只显示这两个链接+标题:
foreach ($comboUserPosts as $value) { ?>
<h2><a href="<?php echo $value['link']; ?>"><?php echo $value['title']; ?></a>
<?php }
答案 0 :(得分:3)
我能想到的最简单的方法是通过链接索引数组(使用array_column()
),然后只提取值......
$comboUserPosts = array_values(array_column($comboUserPosts, null, 'link'));
echo var_export($comboUserPosts, true);
根据上面的测试数据,它给出了......
array (
0 =>
array (
'link' => 'https://example.com/test/test-values-users/',
'dates' => ' 1954',
'title' => 'test values users',
),
1 =>
array (
'link' => 'https://example.com/test/provo-filter/',
'dates' => '1330',
'title' => 'provo filter',
),
)
答案 1 :(得分:2)
您只需首先删除元素dates
,然后使用array_unique
foreach($arr as $k=> &$v){
unset($v['dates']);
}
print_r(array_unique($arr, SORT_REGULAR));
答案 2 :(得分:1)
你可以写这样的代码
<?php
$ar = array (
0 =>
array (
'link' => 'https://example.com/test/test-values-users/',
'dates' => '1920',
'title' => 'test values users',
),
1 =>
array (
'link' => 'https://example.com/test/test-values-users/',
'dates' => ' 1954',
'title' => 'test values users',
),
2 =>
array (
'link' => 'https://example.com/test/provo-filter/',
'dates' => '1600',
'title' => 'provo filter',
),
3 =>
array (
'link' => 'https://example.com/test/provo-filter/',
'dates' => '1450',
'title' => 'provo filter',
),
4 =>
array (
'link' => 'https://example.com/test/provo-filter/',
'dates' => '1330',
'title' => 'provo filter',
),
);
function unique_multidimensional_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$unique = unique_multidimensional_array($ar, 'link');
echo "<pre>";
print_r($unique);
?>
答案 3 :(得分:0)
您可以使用此方法
array_unique($associativeArray,SORT_REGULAR);
使用名称和年龄键定义关联数组 $ associativeArray 。
$associativeArray[] = array("name" => "Yogesh Singh","no"=>4);
$associativeArray[] = array("name" => "Sonarika Singh","no"=>4);