【问题标题】:How to parse an object containing multidimensional array如何解析包含多维数组的对象
【发布时间】:2021-01-08 14:42:22
【问题描述】:

我有一个对象 $userStatus,它通过 API 调用获取以下格式的值。

我无法通过循环分配值。

foreach($usersStatus as $user => $element) {    
        print "[".$user."] => ". $element ."<br />";
    }

php 中的以下脚本允许我打印第一组值,直到键 ["total_time"] => String96) "6m 34s" 但随后我收到以下警告

警告:第 119 行 C:\XAMPP\htdocs\Check-status.php 中的数组到字符串转换 [单位] => 数组

有没有办法,我可以使用循环遍历整个对象,包括两个数组 [0][1] 并将任何值分配给任何变量。

我知道 vardump 会打印整个内容,但我想通过循环或嵌套循环遍历整个对象。

["role"]=>string(7) "learner"
["enrolled_on"]=>string(20) "05/01/2021, 17:44:53"
["enrolled_on_timestamp"]=>string(10) "1609868693"
["completion_status"]=>string(9) "Completed"
["completion_percentage"]=>string(3) "100"
["completed_on"]=>string(20) "06/01/2021, 16:58:23"
["completed_on_timestamp"]=>string(10) "1609952303"
["expired_on"]=>string(0) ""
["expired_on_timestamp"]=>NULL 
["total_time"]=>string(6) "6m 34s"

["units"]=>array(2) {
    [0]=>array(8) {
        ["id"]=>string(4) "2047"
        ["name"]=>string(26) "MyCourse1 2019"
        ["type"]=>string(19) "SCORM | xAPI | cmi5"
        ["completion_status"]=>string(9) "Completed"
        ["completed_on"]=>string(20) "06/01/2021, 16:58:23"
        ["completed_on_timestamp"]=>string(10) "1609952303"
        ["score"]=>NULL 
        ["total_time"]=>string(6) "3m 56s"
    }
            
    [1]=>array(8) {
        ["id"]=>string(4) "2059"
        ["name"]=>string(34) "Assessment - MyCourse1"
        ["type"]=>string(4) "Test"
        ["completion_status"]=>string(9) "Completed"
        ["completed_on"]=>string(20) "06/01/2021, 15:06:56"
        ["completed_on_timestamp"]=>string(10) "1609945616"
        ["score"]=>string(5) "91.67"
        ["total_time"]=>string(6) "2m 38s"
    }
}

感谢您的帮助!

【问题讨论】:

    标签: php arrays object


    【解决方案1】:

    检查 $element 是否为数组以避免这种情况

    foreach($usersStatus as $user => $element) {
            // check if the value is not array
            if (!is_array($element)) {
              print "[".$user."] => ". $element ."<br />";
            } else {
              // value is array do with it whatever you want
              // like another foreach for example
              foreach($element as $key => $value) {
                 // do whatever 
              }
            }     
        }
    

    【讨论】:

      【解决方案2】:

      array_walk_recursive 将满足您的示例。如果类型是数组,它将对数组的每个成员应用一个用户函数,同时递归地这样做。

      array_walk_recursive($arr, function ($val, $key) {
          echo "[" . $key . "] => " . $val . "<br />";
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        • 2012-11-08
        • 2011-12-17
        相关资源
        最近更新 更多