PHP-多维数组检查重复项(无array_unique)

时间:2018-07-20 06:55:11

标签: php arrays if-statement multidimensional-array duplicates

更新

  

我为自己找到了这个问题的答案,并将其发布了,但是我只能在两天内接受。


我创建了这个多维数组:

array (
  0 => 
  array (
    'OrderDate' => '02.11.2018',
    'ClientNumber' => 5500
  )
)

array (
  0 => 
  array (
    'OrderDate' => '02.11.2018',
    'ClientNumber' => 5500
  )
)

array (
  0 => 
  array (
    'OrderDate' => '05.03.2018',
    'ClientNumber' => 5500
  )
)

array (
  0 => 
  array (
    'OrderDate' => '10.12.2018',
    'ClientNumber' => 2200
  )
)

array (
  0 => 
  array (
    'OrderDate' => '10.12.2018',
    'ClientNumber' => 2200
  )
)

该数组不应包含每个ClientNumber的重复OrderDate。

我希望输出看起来像这样:

array (
  0 => 
  array (
    'OrderDate' => '02.11.2018',
    'ClientNumber' => 5500
  )
)

array (
  0 => 
  array (
    'OrderDate' => '05.03.2018',
    'ClientNumber' => 5500
  )
)

array (
  0 => 
  array (
    'OrderDate' => '10.12.2018',
    'ClientNumber' => 2200
  )
)

我应该使用哪种if条件使输出看起来像这样?任何帮助将不胜感激,谢谢!

这是在foreach中调用的我的函数。我尽力检查in_array和array_column,但输出看起来与上面的代码不一样。

$array = array();
function createArray($clientNr, $orderDate){
 if(empty($array)){ // if array is empty, just add
  $array[] = array(
              "OrderDate"=>$orderDate,
              "ClientNumber"=>$clientNr
                 );
 } else {
    if(??????)<--------------------------- // check here if date from clientnumber exists
      $array[] = array(
                   "OrderDate"=>$orderDate,
                   "ClientNumber"=>$clientNr
                  );
    }
 }
}

3 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:-

$data=array();

$data[0]['OrderDate']='02.11.2018';
$data[0]['ClientNumber']='5500';

$data[1]['OrderDate']='02.11.2018';
$data[1]['ClientNumber']='5500';

$new_arr = array_unique($data, SORT_REGULAR);

答案 1 :(得分:0)

尝试以下方法,可以使用array_map或array_unique()函数

$array = array(
  array(
     'OrderDate' => '02.11.2018',
     'ClientNumber' => 5500
  ),
  array(
    'OrderDate' => '02.11.2018',
    'ClientNumber' => 5500
  ),
  array(
    'OrderDate' => '05.03.2018',
    'ClientNumber' => 5500
  ),
  array(
    'OrderDate' => '10.12.2018',
    'ClientNumber' => 2200
  ),
  array(
    'OrderDate' => '10.12.2018',
    'ClientNumber' => 2200
  )
);

$newArr = array_map("unserialize", array_unique(array_map("serialize", $array)));

print_r($newArr);

$newArr1 = array_unique($array, SORT_REGULAR);

print_r($newArr1);

答案 2 :(得分:0)

我做到了!感谢您的方法,但是 这两个对我不起作用:

array_unique($array, SORT_REGULAR);
array_map("unserialize", array_unique(array_map("serialize", $array)));

这是我的解决方案,我添加了一个唯一键,并检查该键是否已存在。

$id = date("Ymd", strtotime($orderDate)).$clientNr; // creates unique key

if(!array_key_exists($id, $array)){ // check if this key exists and add if not

 $array[$id] = array(
              "OrderDate"=>$orderDate,
              "ClientNumber"=>$clientNr
             );
}
相关问题