How can I search value from Multidimensional array using PHP

882
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?

325

Answer

Solution:

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,

508

Answer

Solution:

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
?>

People are also looking for solutions to the problem: php - In Laravel getting error after http://localhost:8000/auth/register url

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.