Reputation: 37
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
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
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