简体   繁体   中英

create a multidimensional array in a loop php

I've done a fair bit of googling and couldn't find anything that works, I'm just getting nothing back, this is probably something simple but there's a lot of variations that don't seem to match what I'm doing.

To give you an overall idea what I'm at, I'm accessing an API and getting back info as an object. There are comments and attachments, these are in separate arrays.

What i want to do is display the comments and attachments all together in the order of the date and time not separately.

I figured the best way is to create a loop through the comments array, then create a loop through the attachment array, then join both and sort by the date (epoch) and then loop through the whole merged loop echoing what i want. That should provide some context, right now i just want to create the multidimensional array for comments and i can figure out the rest.

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

if everything is okay with data, this code will be enough for building such array:

$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);
  • if comment->comments is an array, there is no need to keep it's count separately;
  • foreach is enough for iterating through the array and there is no need to keep separate variable for calculating array index;
  • [] notation will automatically increase array index and assigning array directly will do the trick(ie will result to multi dim array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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