Reputation: 12512
I output a PHP object via a loop but withing this look I have a few nested arrays.
[categories] => Array
(
[0] => Array
(
[0] => Chinese
[1] => chinese
)
[1] => Array
(
[0] => Vietnamese
[1] => vietnamese
)
)
[phone] => 5123355555
I can get the phone like this:
$response->businesses[$x]->phone
How do I get categories (first value) into a string like this:
Chinese, Vietnamese
Upvotes: 1
Views: 57
Reputation: 22158
You can achieve with array_column()
:
$newArray = array_column($response->businesses[$x]->categories, 0);
It returns an array with the column 0
. So the response will be:
print_r($newArray);
//Array ( [0] => Chinese [1] => Vietnamese )
Then you can join it safely:
$newString = implode(",", $newArray)
echo $newString; // "Chinese, Vietnamese"
Upvotes: 3
Reputation: 5524
implode(', ', array_map(function($item) {
return $item[0];
}, $response->businesses[$x]->categories));
Upvotes: 2