简体   繁体   中英

How can I search value from Multidimensional array using PHP

Array ( 
       [0] => Array ( 
                       [id] => 13137 
                       [meta_value] => Chris 
                       [field_id] => 104 
                       [item_id] => 4413 
                       [created_at] => 2015-06-17 17:00:21
                    ) 
       [1] => Array ( 
                       [id] => 13136 
                       [meta_value] => 0.10 
                       [field_id] => 123 
                       [item_id] => 4413 
                       [created_at] => 2015-06-17 17:00:21 
                    )
      );

How would I access the meta_value (Chris) where field_id = 104?

Make use of array_search function

 $key = array_search(104, array_column($array, 'field_id'));
 if($key !== false)
 {
       echo $array[$key]['meta_value'];
 }

Demo

Try this

foreach($array as $k => $v ) {
    if ($v['field_id'] ==104) {
        $value = $v['meta_value'];
    }
}

print_r($value);

Where $array is the variable in which you have above value,

To make the code reusable, you may define a function, like the following:

<?php
$array = [
    ['id' => 13137, 'meta_value' => 'Chris', 'field_id' => 104, 'item_id' => 4413, 'created_at' => '2015-06-17 17:00:21' ],
    ['id' => 13136, 'meta_value' => 0.10,    'field_id' => 123, 'item_id' => 4413, 'created_at' => '2015-06-17 17:00:21' ],
];

function getMetaValue($arr, $field_id) {
    foreach($arr as $subArr)
        if($subArr['field_id']==$field_id)
            return $subArr['meta_value'];
    return null;
}

echo getMetaValue($array, 104); // Chris
echo getMetaValue($array, 123); // 0.10
?>

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