繁体   English   中英

在循环php中创建一个多维数组

[英]create a multidimensional array in a loop php

我已经做了一些谷歌搜索,找不到任何有用的东西,我只是得不到任何回报,这可能是一些简单的东西,但有很多变化似乎与我正在做的不相符。

为了让您全面了解我的目标,我正在访问API并将信息作为对象获取。 有评论和附件,这些是在单独的数组中。

我想要做的是按照日期和时间的顺序一起显示注释和附件,而不是单独显示。

我认为最好的方法是通过comments数组创建一个循环,然后通过附件数组创建一个循环,然后连接两个并按日期(epoch)排序,然后遍历整个合并循环,回显我想要的。 这应该提供一些上下文,现在我只想创建注释的多维数组,我可以弄清楚其余的。

$comments_holder = array();

//total number of comments in the array     
$comment_total = $issue_json->fields->comment->total -1;
$i=1;
while ($i <= $comment_total)
    {
    //this is the date,time and timezone info for each comment
    $raw_date = $issue_json->fields->comment->comments[$i]->updated;

    $comments_holder[$i] = array();

    //convert_sql_time just converts from 2012-11-04T16:33:00.936+600 into epoch time so i can sort the results later based on date
    $comments_holder[$i]['comments_date'] = convert_sql_time($raw_date); 
    $comments_holder[$i]['comments_displayName'] = $issue_json->fields->comment->comments[$i]->author->displayName;
    $comments_holder[$i]['comments_body'] = $issue_json->fields->comment->comments[$i]->body;
    }

如果数据一切正常,这段代码就足以构建这样的数组了:

$comments = $issue_json->fields->comment->comments;
$result = array();

foreach ($comments as $comment) {
  $result[] = array(
    'comments_date' => convert_sql_time($comment->updated),
    'comments_displayName' => $comment->author->displayName,
    'comments_body' => $comment->body,
  );
}

print_r($result);
  • 如果comment-> comments是一个数组,则无需单独保留它的数量;
  • foreach足以遍历数组,并且不需要保留单独的变量来计算数组索引;
  • []表示法将自动增加数组索引并直接分配数组将完成这一操作(即将导致多个dim数组)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM