简体   繁体   中英

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.

I can't manage to get array_unique working as it throws

 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:

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

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

and I use $z for the insert thereafter.

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!)

<?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);

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. If you follow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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