Search code examples
phpmultidimensional-arraycomparison

Compare sub-arrays in foreach loop


I have this array containing sub-arrays which represent different entries:

$array = [
[
    ["Name" => "Auto", "EntryId" => 1234, "LanguageId" => ["PrimaryLangId" => 7, "SubLangId" => 1]],
    ["Name" => "自動車", "EntryId" => 1234, "LanguageId" => ["PrimaryLangId" => 17, "SubLangId" => 1]],
    ["Name" => "car", "EntryId" => 1234, "LanguageId" => ["PrimaryLangId" => 9, "SubLangId" => 1]]
],
[
    ["Name" => "Antrieb", "EntryId" => 5678, "LanguageId" => ["PrimaryLangId" => 7, "SubLangId" => 1]],
    ["Name" => "drive", "EntryId" => 5678, "LanguageId" => ["PrimaryLangId" => 9, "SubLangId" => 1]]
]];

I need to retrieve the value of each "Name" key, but only if the key PrimaryLangId = 7 and there is no other entry with key PrimaryLangId = 17. So in the above example I only want to get "Antrieb", but I only can make my script to get "Auto" and "Antrieb".

Here is what I tried:

foreach ($array as $a) {

for ($i = 0; $i < count($a); $i++) {
    
    if (!in_array(17, $a[$i]['LanguageId']) && $a[$i]['LanguageId']['PrimaryLangId'] == 7) {
        print $a[$i]['Name'] . "\n";
        
    }
}}

The output I get is:

Auto
Antrieb

I understand why I get both "Auto" and "Antrieb" as my if statement only checks inside the sub-array and within this array there obviously is no PrimaryLangId = 17. I'm lacking a comparison against the other sub-arrays. How do I achieve this?


Edit: I'm looking for a way to only get name of the sub-array if the array does not contain a sub array with PrimaryLangId = 17. So basically I need to compare the sub-array against each other.

In my example, I want to get the output:

Auto

Solution

  • foreach ($array as $subArray) {
        $hasNoPrimaryLangId17 = true;
        for ($i = 0; $i < count($subArray); $i++) {
            if ($subArray[$i]['LanguageId']['PrimaryLangId'] == 17) {
                $hasNoPrimaryLangId17 = false;
            }
        }
        if ($hasNoPrimaryLangId17) {
            for ($i = 0; $i < count($subArray); $i++) {
                if ($subArray[$i]['LanguageId']['PrimaryLangId'] == 7) {
                    print $subArray[$i]['Name'] . "\n";
                }
            }
        }
    }