search

Home  >  Q&A  >  body text

Foreach fails to build array in php

Code:

<?php
$arr=array();
foreach($data as $row){
    $arr['name']=$row->user->username;
    $arr['time']=$row->user->time;
};
echo json_encode($arr);
?>

Why does the output json have only one piece of content?

phpcn_u1582phpcn_u15822788 days ago748

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-07-04 13:48:02

    Dear, read the manual more and master the grammar.

    <?php
    $arr=array();
    foreach($data as $row){
        $t['name']=$row->user->username;
        $t['time']=$row->user->time;
        $arr[] = $t;
    };
    echo json_encode($arr);
    ?>

    reply
    0
  • 習慣沉默

    習慣沉默2017-07-04 13:48:02

    <?php
    $arr=array();
    foreach($data as $key=>$row){
        $arr[$key]['name']=$row->user->username;
        $arr[$key]['time']=$row->user->time;
    };
    echo json_encode($arr);
    ?>

    reply
    0
  • Cancelreply