使多维数组唯一的PHP

时间:2014-08-02 05:31:45

标签: php arrays multidimensional-array

我的数组看起来像这样:

  

数组(

    [1] => stdClass Object
        (
            [id] => 225
            [user_id] => 1
            [name] => Blue Quilted Leather Jacket by Minusey - $499

        )

    [2] => stdClass Object
        (
            [id] => 222
            [user_id] => 1
            [name] => Darling New Bathtub by Duravit - $6300

        )
   [3] => stdClass Object
        (
            [id] => 222
            [user_id] => 1
            [name] => Darling New Bathtub by Duravit - $6300

        ) 
     

我有一系列产品,我需要确保它们是独一无二的。需要通过id使这个数组唯一。这些数组是通过推送值生成的。

我现在试图解决这个问题超过一个星期了,但是我没办法解决这个问题。我知道它应该很容易......但无论如何 - 我不明白:D

3 个答案:

答案 0 :(得分:3)

你能试试吗,

$input = array ('1' => array(
            'id' => 225,
            'user_id' => 1,
            'name' => 'Blue Quilted Leather Jacket by Minusey - $499'

        ),
        '2' => array(
                'id' => 222,
                'user_id' => 1,
                'name' => 'Darling New Bathtub by Duravit - $6300'

        ),
        '3' => array(
                'id' => 222,
                'user_id' => 1,
                'name' => 'Darling New Bathtub by Duravit - $6300'

        )                   
  );    

    $UniqueArray = array();
    foreach($input as $key=>$value){   // rebuild your array    
        //$id = $value['id']; //build array with unique key value
        $id = $value->id; //object
        $UniqueArray[$id] = $value;
    }

   print_r($UniqueArray);

<强>输出:

   Array
   (
        [225] => Array
        (
                [id] => 225
                [user_id] => 1
                [name] => Blue Quilted Leather Jacket by Minusey - $499
        )

        [222] => Array
        (
                [id] => 222
                [user_id] => 1
                [name] => Darling New Bathtub by Duravit - $6300
        )

   )

答案 1 :(得分:2)

基本思路是循环使用产品并保存您遇到的产品。如果已找到产品,请跳过它。

<?php
function array_unique_by_key($array, $key = 'id') {
    $found = array(); // Encountered IDs
    $out = array(); // Output array

    foreach ($array as $value) {
        if (!array_key_exists($key, $value)) throw new Exception('Can\'t find key "' . $key . '"');
        $id = $value[$key];

        // If already encountered, skip
        if (in_array($id, $found)) continue;

        // Otherwise, add to found values and to output array
        $found[] = $id;
        $out[] = $value;
    }

    return $out;
}

用法:

$unique_products = array_unique_by_key($your_products, 'id');

答案 2 :(得分:2)

试试这个简单的代码

$arr_new = array();
$arr_temp_ids = array();
foreach($your_array as $key=>$arr_obj)
{
    $arr_val = get_object_vars($arr_obj);
    if(!isset($arr_temp_ids[$arr_val['id']]))
    {
        $arr_new[] = $arr_obj;
        $arr_temp_ids[$arr_val['id']] = true;
    }
}
var_dump($arr_new); // resultant array