user3131412
user3131412

Reputation: 37

Putting multi-dimensional array into a string

I have an $_POST array that looks like this.

Array (
    [burrito] => Cilantro
    [pizza] => Array ( [0] => Avocado [1] => Italian Sausage [2] => pepperoni )
) 

I need $_POST variable to be dynamic. So, burrito & pizza is not fixed variable.

I want this to look like:

burrito=>Cilantro , pizza=>(Avocado, Italian Sausage, pepperoni)

I suspect I need to use:

foreach($_POST as $key => $value){

    foreach($_POST[$key] as $d => $k){

    }

}

And the implode() function.

But I am stuck here. Whatever I do, the result would not come out.

Upvotes: 0

Views: 140

Answers (2)

Lucian Depold
Lucian Depold

Reputation: 2019

You can use json_encode() to convert an array into a string. Then your array will look like this:

{"burrito":"Cilantro","pizza":["Avocado","Italian Sausage","pepperoni"]}

You can also convert the string back into an array using json_decode().

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

You are on the right track with implode(). But since you have values which only contain a string and some which contain an array, you have to check for that.

So you can do something like this:

Simply loop through your array and if the value is_array() then return the imploded array back, otherwise just the single value, e.g.

foreach($_POST as $k => $v) {
    echo "$k => " . (is_array($v) ? "(" . implode(",", $v). ")" : $v) . "<br>";
}

Upvotes: 1

Related Questions