在包含多维数组的关联数组中存在组合

问题描述:

I have an associative array witch contains a multidimensional one.

Here's the famous array:

$existingCategoryAttributesNames[] = array(
    'attributeName'     => $existingAttributeOverridedAttribute->getAttribute()->getName(),
    'categoryName'      => $existingCategory->getName(),
    'categoryAttribute' => $existingAttributeOverridedAttribute);

I would like to test if a combination of attributeName and categoryName exists and gets the categoryAttribute associated.

How can I do that? If the combination exists I modify it, if not I add something in my BDD. With my actual code (combination of a foreach and if (in_array)) it compares every single line! If the combination doesn't match with the first element, it adds, even if it matches with the fifth for example..

Examples with values:

My array in witch I have to compare a combination :

[6] =>
  array(3) {
   'attributeName'     => string(5) "doors"
   'categoryName'      => string(8) "Voitures"
   'categoryAttribute' => "example"   
}

You can build another array with indices for attribute and category name:

$combinations = [];
array_walk($existingCategoryAttributesNames, function($item) {
    $combinations[$item['attributeName']][$item['categoryName']] = $item['categoryAttribute'];
});

Then your test becomes:

if (isset($combinations['doors']['Voiture'])) {
    // do something
}

See also: array_walk