【问题标题】:Looping Through Multi-Dimensional Array in PHP在 PHP 中循环遍历多维数组
【发布时间】:2014-01-20 03:47:58
【问题描述】:

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

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 值。

【问题讨论】:

  • 您是否尝试过使用类型检查进行递归?这可能会有所帮助:stackoverflow.com/questions/15917022/…
  • @josh-austin 你可能从问题本身就可以看出我是个新手,所以递归现在不适合我。

标签: php multidimensional-array


【解决方案1】:

假设您的数组名称是$mdarr,并且每次数组的构造都大致相同,那么简单如下:

$values_i_want = $mdarr['data']['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);
        }
    }
}

【讨论】:

    【解决方案2】:

    使用以下内容作为基础。我重建了你的数组,这样我就可以搞砸了。

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

    【讨论】:

      【解决方案3】:

      如果数组结构不会改变,而您只需要 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
      

      【讨论】:

        猜你喜欢
        • 2012-04-21
        • 2011-01-02
        • 2016-02-16
        • 2021-09-17
        • 1970-01-01
        • 2010-10-24
        相关资源
        最近更新 更多