为了账号安全,请及时绑定邮箱和手机立即绑定

Json 编码数组值

Json 编码数组值

PHP
饮歌长啸 2022-01-08 16:54:03
如何将来自特定数组键的所有值分配给 json 值。$cars = Array ( [0] => Array ( [category] => Most Selling [title] => BMW [price] => 20000 ) [1] => Array ( [category] => Most Selling [title] => Jeep [price] => 15000) [2] => Array ( [category] => Most Selling [title] => Lexus [price] => 18000  ) )foreach ( $cars as $car) {     $data = [    'model' => 'new',    'company' => $car['title'],];}$json = json_encode($data); 现在当我输出 $json 我得到:{"model":"new","company":"Lexus"}为什么它没有像这样分配所有标题值?{"model":"new","company":"BMW, Jeep, Lexus"}
查看完整描述

3 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

你不需要foreach循环。您可以使用implode和array_column


$data = [

  'model'   => 'new',

  'company' => implode(', ',array_column($cars, 'title'))

];

echo $json = json_encode($data);

现场演示:https : //3v4l.org/9IrW8


查看完整回答
反对 回复 2022-01-08
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

这应该会产生您需要的输出。


$data = [

    'model' => 'new',

    'company' => '',

];

foreach ( $cars as $car) {

     $data['company'] .= $car['title'] . ', ';

}


$data['company'] = substr($data['company'], 0, -2); // remove last comma and space

$json = json_encode($data);


查看完整回答
反对 回复 2022-01-08
?
慕少森

TA贡献2019条经验 获得超9个赞


$companyString = implode(', ', array_column($cars, 'title'));


$data = [

   'model' => 'new',

   'company' => $companyString

];


$json = json_encode($data); 


查看完整回答
反对 回复 2022-01-08
  • 3 回答
  • 0 关注
  • 174 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号