Reputation: 1111
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.
Upvotes: 0
Views: 39
Reputation: 78994
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
Upvotes: 1