简体   繁体   中英

How to retrieve value from pdo array

I am trying to get the value for total from this array to put into a variable:

Array ( 

[0] => Array ( [Variable_name] => var1 [Value] => 2 ) 
[1] => Array ( [Variable_name] => total [Value] => 1 ) 
[2] => Array ( [Variable_name] => var3 [Value] => 0.002 ) 

)

PHP:

$data = $array->fetchAll(PDO::FETCH_ASSOC);

echo $data[1]['total'];

foreach ($data as $result){
     echo $result['total'];
}

foreach ($data as $result){
     echo $result[1]['total'];
}

None of the above echo the variable, if I use print_r($array->fetchAll(PDO::FETCH_ASSOC)); it prints the array, what is the correct way to do this?

In short: I want to get the value from the key Value , where the Variable_name is holding the value total . Here in this example it would be 1.

Here's one way to get the variable names as indexes in an array:

$vars = array_column($data, null, 'Variable_name');

echo $vars['total']['Value'];  // displays 1
echo $vars['var3']['Value'];   // displays 0.002 

Or if you only need the value for each one:

$vars = array_column($data, 'Value', 'Variable_name');

echo $vars['total'];  // displays 1
echo $vars['var3'];   // displays 0.002 

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