简体   繁体   中英

Search in multidimensional array by several values

I have an array which I'm sure there are some duplicate values in it, I want to search in this array and find the duplicate values and return the key of that array.

let me explain with an example, this is my array:

[
  0 => [
      'name' => 'name0',
      'family' => 'family0',
      'email' => 'email0@sample.com',
      'rate' => 10
  ],
  1 => [
      'name' => 'name1',
      'family' => 'family1',
      'email' => 'email1@sample.com',
      'rate' => 4
  ],
  2 => [
      'name' => 'name0',
      'family' => 'family0',
      'email' => 'email0@sample.com',
      'rate' => 6
  ]
];

Now, I want to search in this array by name , family , and email at the same time and return the key of the parent (in this example 0 and 2). because I want to create a new array like this :

[
  0 => [
      'name' => 'name0',
      'family' => 'family0',
      'email' => 'email0@sample.com',
      'rate' => [
          10,
          6
      ]
  ],
  1 => [
      'name' => 'name1',
      'family' => 'family1',
      'email' => 'email1@sample.com',
      'rate' => [
          4
      ]
  ],
];

How can I do this in PHP?

You can use array-reduce and use the 3 similar fields as keys.

Define a function who create the key and set or add rate:

function combineRate($carry, $item) {
    $k = implode('###', array($item['name'], $item['family'], $item['email']));
    if (isset($carry[$k]))
        $carry[$k]['rate'][] = $item['rate'];
    else {
        $item['rate'] = [$item['rate']];
        $carry[$k] = $item;
    }
    return $carry;
}

Call it with empty array:

$res = array_values(array_reduce($a, 'combineRate', array()));

Live example: 3v4l

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