簡體   English   中英

在PHP中循環遍歷多維數組

[英]Looping Through Multi-Dimensional Array in PHP

我查看了許多類似的示例,但似乎仍然無法弄清楚如何循環並從該數組中回顯值。 應該很簡單,但是我很密集。 感謝幫助。

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

我試圖返回“值”數組的int值。

舉例來說,給定數組的名稱為$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);
        }
    }
}

使用以下內容作為基礎。 我重建了您的陣列,以便可以弄亂它。

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

如果數組結構不會改變,而您只想要int值包含在values ,則可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM