Reputation: 473
I've looked up a bunch of similar examples but still can't seem to figure out how loop through and echo the values from this array. Should be simple, but I'm dense. Help is appreciated.
array(2) { ["legend_size"]=> int(1) ["data"]=> array(2) { ["series"]=> array(2) { [0]=> string(10) "2014-01-17" [1]=> string(10) "2014-01-18" } ["values"]=> array(1) { ["Begin Session"]=> array(2) { ["2014-01-17"]=> int(1073) ["2014-01-18"]=> int(1122) } } } }
I'm trying to return the int values for the "values" array.
Upvotes: 0
Views: 96
Reputation: 4253
If the array structure is not going to change, and you just want the int values inside values
, you could do the following:
//Create array
$some_array = array(
"legend_size" => 5,
"data" => array(
"series" => array(0 => "2014-01-17", 1 => "2014-01-18" )
"values" => array(
"Begin Session" => array("2014-01-17" => 1000, "2014-01-18" => 1000)
)
)
);
//Get values
foreach($some_array['data']['values'] as $key => $value)
{
if(is_array($value))
{
echo $key . " => ";
foreach($value as $key2 => $value2)
{
echo " " . $key2 . " => " . $value2;
}
}
else
{
echo $key . " => " . $value;
}
}
This will give you an output like this:
Begin Session =>
2014-01-17 => 1000
2014-01-18 => 1000
Upvotes: 0
Reputation: 776
Given the name of your array is, for the sake of example, $mdarr
, and that the construction of the array is going to be roughly the same every time, it is as simple as:
$values_i_want = $mdarr['data']['values'];
If the values array you are looking for is going to be in different array depths in different cases, recursion combined with type checking will do the trick:
//returns values array or nothing if it's not found
function get_values_array($mdarr) {
foreach ($mdarr as $key => $val) {
if ($key == 'values') {
return $val;
} else if (is_array($val)) {
return get_values_array($val);
}
}
}
Upvotes: 1
Reputation: 1605
Use the following as a base. I reconstructed your array so I could mess around with it.
$turtle = array('legend_size' => 'int(1)', 'data' =>array('series' => array('string(10) "2014-01-17"', '[1]=> string(10) "2014-01-18"'), 'values' => array('Begin_Session' =>array('2014-01-17' => 'int(1073)', '2014-01-18' => 'int(1122)'))));
// This is where you "navigate" the array by using [''] for each new array you'd like to traverse. Not sure that makes much sense, but should be clear from example.
foreach ($turtle['data']['values']['Begin_Session'] as $value) {
$match = array();
// This is if you only want what's in the parentheses.
preg_match('#\((.*?)\)#', $value, $match);
echo $match[1] . "<br>";
}
Upvotes: 0