Json encode Arrays value

Tod*_*Tod 0 php arrays api wordpress json

如何将特定数组键的所有值分配给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); 
Run Code Online (Sandbox Code Playgroud)

现在,当我输出$ json时,我得到:

{"model":"new","company":"Lexus"}
Run Code Online (Sandbox Code Playgroud)

为什么不这样分配所有标题值?

{"model":"new","company":"BMW, Jeep, Lexus"}
Run Code Online (Sandbox Code Playgroud)

Rak*_*har 5

您不需要foreach为此的循环。您可以使用implodearray_column

$data = [
  'model'   => 'new',
  'company' => implode(', ',array_column($cars, 'title'))
];
echo $json = json_encode($data);
Run Code Online (Sandbox Code Playgroud)

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