如何修剪数组以仅显示非重复值?

时间:2015-07-21 07:44:24

标签: php arrays

我正在努力解决数组结果:

$result = Db::getInstance()->ExecuteS( $sql ); 

    $this->smarty->assign( array(
         'result' => $result
    ));

这是我的阵列:

Array ( 
[0] => Array ( [id_tag] => 2 [id_post] => 5 [id_smart_blog_post_shop] => 5 [id_smart_blog_post] => 5 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
[1] => Array ( [id_tag] => 2 [id_post] => 6 [id_smart_blog_post_shop] => 6 [id_smart_blog_post] => 6 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
[2] => Array ( [id_tag] => 2 [id_post] => 7 [id_smart_blog_post_shop] => 7 [id_smart_blog_post] => 7 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
[3] => Array ( [id_tag] => 2 [id_post] => 8 [id_smart_blog_post_shop] => 8 [id_smart_blog_post] => 8 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
[4] => Array ( [id_tag] => 2 [id_post] => 9 [id_smart_blog_post_shop] => 9 [id_smart_blog_post] => 9 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
[5] => Array ( [id_tag] => 4 [id_post] => 10 [id_smart_blog_post_shop] => 10 [id_smart_blog_post] => 10 [id_shop] => 1 [id_lang] => 1 [name] => XPPower ) 
[6] => Array ( [id_tag] => 2 [id_post] => 11 [id_smart_blog_post_shop] => 11 [id_smart_blog_post] => 11 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
[7] => Array ( [id_tag] => 2 [id_post] => 12 [id_smart_blog_post_shop] => 12 [id_smart_blog_post] => 12 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
[8] => Array ( [id_tag] => 4 [id_post] => 13 [id_smart_blog_post_shop] => 13 [id_smart_blog_post] => 13 [id_shop] => 1 [id_lang] => 1 [name] => XPPower ) 
) 

并且,我想要的只是显示一次名称值:

Microchip, XPPower

而不是这样:

Microchip, Microchip, Microchip, Microchip, Microchip, XPPower, Microchip, Microchip, XPPower

我正在尝试使用array_unique仅显示非重复值,但它可以部分显示并仅显示。

Microchip值一次并离开XPPower

$tags = Db::getInstance()->ExecuteS( $sql ); 
$result = array_values(array_unique($tags));

$this->smarty->assign( array(
     'result' => $result
));

阵列打印:

Array ( 
 [0] => Array ( [id_tag] => 2 [id_post] => 5 [id_smart_blog_post_shop] => 5 [id_smart_blog_post] => 5 [id_shop] => 1 [id_lang] => 1 [name] => Microchip ) 
 ) 

这是$ sql函数,如果有人想知道

$sql = 'SELECT * FROM '._DB_PREFIX_.'smart_blog_post_tag p INNER JOIN 
            '._DB_PREFIX_.'smart_blog_post_shop s ON p.id_post=s.id_smart_blog_post AND s.id_shop = '.(int) Context::getContext()->shop->id.' INNER JOIN 
            '._DB_PREFIX_.'smart_blog_tag t ON p.id_tag= t.id_tag where t.id_lang = '.(int)$id_lang.' LIMIT '.$limit;

2 个答案:

答案 0 :(得分:1)

$names = array();
foreach ($tags as $tag) {
    $names[$tag['name']] = 1;
}
print_r(array_keys($names));

答案 1 :(得分:0)

你不能使用第二个数组来捕获独特的结果吗?像:

$uniq_results=array();
foreach ($results as $r) {
    if (!in_array($r["name"],$uniq_results)) {
        $uniq_results[]=$r["name"];
    }
} unset($r);

var_dump($uniq_results);
// should print only the unique values