0

How to assign to a json value all values from particular array keys.

$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); 

Now when i output $json i get:

{"model":"new","company":"Lexus"}

Why it doesn't assign all title values like this?

{"model":"new","company":"BMW, Jeep, Lexus"}
Tod
  • 187
  • 3
  • 13

4 Answers4

5

You don't need foreach Loop for that. You can use implode and array_column

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

Live demo : https://3v4l.org/9IrW8

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
1

This should proiduce the output you need.

$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);
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
0
$data = [];
foreach ( $cars as $car) {
     $data[] = [
        'model' => 'new',
        'company' => $car['title'],
    ];
}
Chris Hemmens
  • 367
  • 2
  • 11
0

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

$data = [
   'model' => 'new',
   'company' => $companyString
];

$json = json_encode($data); 
Nico Shultz
  • 1,872
  • 1
  • 9
  • 23