1

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
3
  • just implode the array. Commented Mar 3, 2016 at 17:06
  • @FrayneKonok NO. Read the question. Commented Mar 3, 2016 at 17:07
  • @santa, did you need this through an function or a loop in raw code of php? Commented Mar 3, 2016 at 17:10

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, this is it, i was looking for it it in the Manual.
What are you looking for? The array_column() function? I share the direct link to php.net
Because i am not an expert, so i was looking for a function that can do the job, so i got late to answer, But one person give me a negative vote. Its not my wrong that i did a answer that is same to your answer.
I'm not downvoted you, but I think that your efforts was fine. Sorry.
2
implode(', ', array_map(function($item) {
       return $item[0];
}, $response->businesses[$x]->categories));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.