简体   繁体   中英

How can I get a value from an array by a child array value?

I've a huge problem. Somehow I need to get the variation_id from an array based on a value of a child array:

$array = [
    [
        'attributes'   => [
            'attribute_art-der-karte' => 'Rot'
        ],
        'variation_id' => '222'
    ],
    [
        'attributes'   => [
            'attribute_art-der-karte' => 'Green'
        ],
        'variation_id' => '221'
    ]
];

So in my case I've two things available:

  1. The key attribute_art-der-karte
  2. The value Rot

I found nothing here instead of a sorting. Any idea? Thanks!

Simply loop over the array and return the variation ID when your condition is met (an attribute exists with the given key and the given value):

function findVariationId(array $array, string $attrName, string $attrValue): ?string {
    foreach ($array as $entry) {
        if (($entry['attributes'][$attrName] ?? null) === $attrValue) {
            return $entry['variation_id'];
        }
    }

    return null;
}

Demo

An additional option using array_search() and array_column() :

<?php 

$array = [
    ['attributes' => ['attribute_art-der-karte' => 'Rot'], 'variation_id' => '222'],
    ['attributes' => ['attribute_art-der-karte' => 'Green'], 'variation_id' => '221']
];

$key = array_search (
    'Rot', 
    array_column(array_column($array, 'attributes'), 'attribute_art-der-karte')
);
echo "variation_id: ". (($key === false) ? 'Not found' : $array[$key]["variation_id"]);

?>

Output:

variation_id: 222

You can also use array filter for this

<?php
$array = [
    [
        'attributes'   => [
            'attribute_art-der-karte' => 'Rot'
        ],
        'variation_id' => '222'
    ],
    [
        'attributes'   => [
            'attribute_art-der-karte' => 'Green'
        ],
        'variation_id' => '221'
    ]
];

function findByAttribute ($arr, $value) {
    $result = array_filter($arr, function($elem) use($value){
     return $elem['attributes']['attribute_art-der-karte'] == $value;
    });
    
    if ($result) {
       return array_shift($result)['variation_id'];
    }
    return '';
}

var_dump(findByAttribute($array, 'Rot')); // gives '222'
var_dump(findByAttribute($array, 'a')); // returns ''
var_dump(findByAttribute($array, 'Green')); // gives 221

You can access the element variation_id using foreach

// One way using loops identify the non-array element
foreach($array as $ele){
    if(!is_array($ele)){
        print_r($ele);
    }
}

// Otherway for direct calling
print_r($array['variation_id']);

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