[英]how to build multi-dimentional array using foreach in php or laravel
我想在 controller 中生成一个多维数组,以便在视图上显示数据。
我试过这个: -
$data2 = [];
foreach ($batch->details as $member_id){
$data2['details'][] = $member_id;
$invoices = $member_id->invoice_id;
$invoice_ids = explode(',', $invoices);
$payments = Payment::with('codes')->whereIn('id', $invoice_ids)-
>get();
$data2['details'][]['payments'] = $payments->toArray();
}
我得到这种类型的数组:-
'batch'=>array('id'=>1,
'name'=>"test",
"detail"=>array(0=>array( 'id'=>1,
'name'=>"tedsadst1",
'amount'=>30)
1=>array( 'id'=>3,
'name'=>"dsadsad",
'amount'=>30),
2=>array('id'=>4,
'name'=>"dsadasddsa",
'amount'=>30)
)
);
'payment'=>array(0=>array(0=>array('id'=>1,'name'=>"hello",
'amount'=>30,'other'=>"hello"
),
1=>array('id'=>3,'name'=>"demo",
'amount'=>330,'other'=>"world"
),
2 => array('id'=>7,'name'=>"dsad",
'amount'=>90,'other'=>"dasd")
)
)
我想要这种类型的多维数组:-
array('batch'=>array('id'=>1,
'name'=>"test",
"detail"=>array(0=>array('id'=>1,
'name'=>"test1",
'amount'=>30
"payment"=>array(0=>array(
0=>array('id'=>1,
'name'=>"hello",
'amount'=>30,
'other'=>"hello"),
1=>array('id'=>3,
'name'=>"demo",
'amount'=>330,
'other'=>"world"),
2 => array('id'=>7,
'name'=>"dsad",
'amount'=>90,
'other'=>"dasd")
)
)
),
1=>array('id'=>2,
'name'=>"test2",
'amount'=>60,
"payment"=>array(
0=>array(0=>array(
'id'=>9,
'name'=>"dsada",
'amount'=>852,
'other'=>"dsadsa"),
)
)
),
2=>array('id'=>3,
'name'=>"test3",
'amount'=>70.
"payment"=>array(
0=>array(0=>array(
'id'=>15,
'name'=>"hgfh",
'amount'=>30,
'other'=>"hehretllo"),
1=>array('id'=>17,
'name'=>"dsterad,
'amount'=>950,
'other'=>"gdfgg")
)
)
)
)
)
如何使用 foreach 或数组函数获得这样的多维数组我正在使用两个 foreach 但我没有得到这样的数组。 所以请帮助我。 谢谢你
试着让它像这样。
$data2 = [];
foreach ($batch->details as $member_id){
$invoices = $member_id->invoice_id;
$invoice_ids = explode(',', $invoices);
$payments = Payment::with('codes')->whereIn('id', $invoice_ids)-
>get();
$newarray = array('details'=>$member_id,array('payments'=>$payments->toArray()));
$data2[] = $newarray;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.