简体   繁体   English

获得具有不同值的数组的更优雅方法

[英]More elegant way of getting array with distinct values

I have this array: 我有这个数组:

$array[] = [
      'a' => $a,
      'b' => $b,
];

The array contains of let's say 10 entries, $a can be in there with the same value many times and I need only one of those entries for a db insert. 该数组包含10个条目,$ a可以多次使用相同的值存在,而对于数据库插入,我只需要其中一个条目即可。

I can't manage to get array_unique working as it throws 我无法使array_unique正常工作

 array to string conversion

error when trying to use it like 尝试使用它时出现错误

 $result = array_unique($array);

I now made a little foreach loop that feels just wrong to do so: 我现在做了一个foreach循环,这样做感觉是错误的:

    $z = [];
    foreach ($array as $x) {

        if (@!in_array($x['a'],$z)) {
            $z[] = $x['a'];
        }
    }

and I use $z for the insert thereafter. 然后我将$ z用于插入。

Can someone point me in the right direction of how to distinct my array values? 有人可以为我指出如何区分数组值的正确方向吗?

This should work for you: 这应该为您工作:

( $result = array_unique($array); this didn't worked, because you have a multidimensional array!) $result = array_unique($array);这没有用,因为您有多维数组!)

<?php


    //Example data
    $array[] = [
          'a' => 1,
          'b' => 1,
          'c' => 1,
          'd' => 2,
          'e' => 2,

    ];

    $array = array_map("array_unique", $array);
    print_r($array);

?>

Output: 输出:

Array ( [0] => Array ( [a] => 1 [d] => 2 ) )

Based on your array that is two dimensional, you would need: 基于二维数组,您将需要:

$array = array_map('array_unique', $array);

Or if you don't need a two dimensional array, just use: 或者,如果您不需要二维数组,请使用:

$array = [
      'a' => $a,
      'b' => $b,
];

And then: $array = array_unique($array); 然后: $array = array_unique($array);

One thing not mentioned is that arrays are built in unique, if you can manage the keys for them yourself. 没有提到的一件事是,如果您可以自己管理键,则数组是内置的。 Associative arrays can only have the key once. 关联数组只能具有一次密钥。 So I like to do is use the primary key or a unique identifier for the key. 所以我喜欢做的是使用主键或键的唯一标识符。

You can't have an array with the same keys like this. 这样的数组不能具有相同的键。

array(
     'a' => $a
     'a' => $b
)

Because the key a is already a unique identifier. 因为密钥a已经是唯一标识符。 If you follow. 如果您遵循。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM