有没有更好的方法在PHP中追加多维数组?

时间:2014-12-18 14:31:32

标签: php arrays multidimensional-array append

我设法做到这一点,它完全符合我的需要,但是,我觉得应该有更整洁的东西。

$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"}]

我希望已有一个重复的问题。请帮助我找到更好的方法来做到这一点,也许是我可以学习的教程或文档,我会非常感激。提前致谢!

1 个答案:

答案 0 :(得分:2)

你的第二种方法的障碍是每次你做$ 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);