在PHP中循环使用多维数组

时间:2014-01-20 03:47:58

标签: php multidimensional-array

我查了一堆类似的例子,但似乎无法弄清楚如何循环并回显此数组中的值。应该很简单,但我很密集。感谢帮助。

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) } } } } 

我正在尝试返回“values”数组的int值。

3 个答案:

答案 0 :(得分:1)

鉴于您的数组的名称,例如$mdarr,并且数组的构造每次都大致相同,它就像这样简单:

$values_i_want = $mdarr['data']['values'];

如果您要查找的values数组在不同的情况下将处于不同的数组深度,则递归与类型检查结合将起到作用:

//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);
        }
    }
}

答案 1 :(得分:0)

使用以下作为基础。我重建了你的阵列,所以我可以搞砸它。

$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>";
}

答案 2 :(得分:0)

如果数组结构不会改变,并且您只想要values内的int值,则可以执行以下操作:

//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;
    }
}

这将为您提供如下输出:

Begin Session =>
    2014-01-17 => 1000
    2014-01-18 => 1000