I have a 3d array:
{
"code": num,
"payload": [
{
"2nd array": [
{
"msg": "some message",
"val": "some val"
}
]
}
]
}
I need to print it without the 2nd array
value so, like this:
{
"code": num,
"payload": [
{
"msg": "some msg"
}
]
}
Here's how I make the array:
foreach ($orig_array as $arr) {
$res[$i]["2nd array"][] = array(
"msg" => $arr["some_message"],
"val" => $arr["some_value"],
);
}
Is there a simple way to do this that I'm not seeing? I have tried to flatten the array or loop through it before sending the response, but I can't get it into that shape.
EDIT:
I thought of removing just the 2nd array, but I can't change that because it's not my code, it's legacy, and it would break many other things.
CodePudding user response:
#just to get the data from your example, the payload
$args = '[
{
"2nd array": [
{
"msg": "some message",
"val": "some val"
}
]
},
{
"2nd array": [
{
"msg": "some message",
"val": "some val"
}
]
}
]';
$arr = json_decode($args,true);
#that is what you can do in 1 line
$arr = array_merge(...array_map(fn($a) => $a['2nd array'] ,$arr));
#then use $arr in the response
var_export($arr);
EDIT: Switched to array_map version
CodePudding user response:
$arr = '{
"code": 1,
"payload": [
{
"2nd array": [
{
"msg": "some message",
"val": "some val"
}
]
},
{
"2nd array": [
{
"msg": "some message",
"val": "some val"
}
]
}
]
}';
$arr = json_decode($arr,true);
$new_arr = [];
foreach($arr['payload'] as $key => $inside){
foreach($inside as $n => $val ) {
$new_arr[] = current($val);
unset($arr['payload'][$key]);
}
}
$arr['payload'] = $new_arr;
print_r($arr);