繁体   English   中英

有没有更好的办法在php中附加多维数组?

[英]is there any better way to append multidimensional array in php?

我设法做到了,它完全可以满足我的需要,但是,我觉得应该有一些更整洁的东西。

$shifts = Shift::all(); //I am working with laravel
$shiftObj = array();
$i =0; //I create this temp var to fill the sub object block
foreach($shifts as $shift){
    $shiftObj[$i]['campaign'] = Campaign::find($shift->campaign_id)->name;
    $shiftObj[$i]['place'] = Places::find($shift->place_id)->name;
    $shiftObj[$i]['shift_date'] = $shift->shift_date;
    $shiftObj[$i]['start_time'] = $shift->start_time;
    $shiftObj[$i]['end_time'] = $shift->end_time;
    $i++;
}
return json_encode($shiftObj);

通过此代码,我得到以下响应:

[{"campaign":"camp1","place":"store1","shift_date":"2014-12-09","start_time":"2014-12-09 00:00:00","end_time":"2014-12-09 15:01:00"},{"campaign":"camp2","place":"store2","shift_date":"2014-12-02","start_time":"2014-12-02 01:00:00","end_time":"2014-12-02 02:00:00"},{"campaign":"camp3","place":"store3","shift_date":"2014-12-30","start_time":"2014-12-30 16:00:00","end_time":"2014-12-31 05:00:00"}] 

然后我做了以下。 (认为​​我发现“更好的方法”)。

    $shifts = Shift::all();
    $shiftObj = array();

foreach($shifts as $shift){
    $shiftObj[]['campaign'] = Campaign::find($shift->campaign_id)->name;
    $shiftObj[]['place'] = Places::find($shift->place_id)->name;
    $shiftObj[]['shift_date'] = $shift->shift_date;
    $shiftObj[]['start_time'] = $shift->start_time;
    $shiftObj[]['end_time'] = $shift->end_time;

}
return json_encode($shiftObj);

我得到了这个结果:

[{"campaign":"camp1"},{"place":"store1"},{"shift_date":"2014-12-09"},{"start_time":"2014-12-09 00:00:00"},{"end_time":"2014-12-09 15:01:00"},{"campaign":"camp2"},{"place":"store2"},{"shift_date":"2014-12-02"},{"start_time":"2014-12-02 01:00:00"},{"end_time":"2014-12-02 02:00:00"},{"campaign":"camp3"},{"place":"store3"},{"shift_date":"2014-12-30"},{"start_time":"2014-12-30 16:00:00"},{"end_time":"2014-12-31 05:00:00"}]

我希望已经有一个重复的问题。 请帮助我找到更好的方法,也许是我可以学习的教程或文档,我将不胜感激。 提前致谢!

第二种方法遇到的障碍是每次执行$ shiftObj []时,您将在$ shiftObj末尾推送一个仅包含您的一个属性的新数组。

因此,您需要像在第一种方法中那样指定数组键,或者像这样一次定义要推送的整个数组:

$shifts = Shift::all();
$shiftObj = array();

foreach($shifts as $shift){
  $shiftObj[] = array(
    'campaign' => Campaign::find($shift->campaign_id)->name,
    'place'    => Places::find($shift->place_id)->name,
    'shift_date' => $shift->shift_date,
    'start_time' => $shift->start_time,
    'end_time' => $shift->end_time
  );
}

return json_encode($shiftObj);

暂无
暂无

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

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