There is an application currently under development at Ravel, and I would like to treat nested data as a single array, but I am having a hard time because I do not know how to do it.
The forms we want to achieve are as follows:
There are two data in the array below, but it is assumed that there are more than 100 data.
I'd like to turn it around in a loop, but if anyone knows, please advise me.
·Original data
array:2[
0 = > array:3 [
"id" = > "0 GPHKD"
"target_layer" = > "Men and women in their teens (T-tier)"
"key" = > array:2 [
0 = > array:2 [
"id" = > 10
"product_name" = > "coffee"
]
1 = > array:2 [
"id" = > 9
"product_name" = > "coffee mug"
]
]
]
1 = > array:3 [
"id" = > "0 GPHKC"
"target_layer" = > "Men and women 20-34 years old (M1 F1 layer)"
"key" = > array:2 [
0 = > array:2 [
"id" = > 10
"product_name" = > "coffee"
]
1 = > array:2 [
"id" = > 9
"product_name" = > "coffee mug"
]
]
]
]
·The form you want to realize
array:2[
0 = > array:3 [
"id" = > "0 GPHKD"
"target_layer" = > "Men and women in their teens (T-tier)"
"item_id1" = > "10"
"product_name1" = > "coffee"
"item_id2" = > "9"
"product_name2" = > "coffee mug"
]
]
1 = > array:3 [
"id" = > "0 GPHKC"
"target_layer" = > "Men and women 20-34 years old (M1 F1 layer)"
"item_id1" = > "10"
"product_name1" = > "coffee"
"item_id2" = > "9"
"product_name2" = > "coffee mug"
]
]
]
The easiest way is to create a new array using nesting loops.
For example, the code below.
Sample data:
$a=[
[
"id" = > "0 GPHKD",
"target_layer" = > "Men and Women in their teens (T-tier),
"key" = > [
[
"id" = > 10,
"product_name" = > "coffee"
],
[
"id" = > 9,
"product_name" = > "coffee mug"
]
]
],
[
"id" = > "0 GPHKC",
"target_layer" = > "Men and women 20-34 years old (M1 F1 layer),
"key" = > [
[
"id" = > 10,
"product_name" = > "coffee"
],
[
"id" = > 9,
"product_name" = > "coffee mug"
]
]
]
];
nesting loop:
$newList=[];
foreach($a as$key=>$val){
$new=[
"id" = > $val ["id" ],
"target_layer" = > $val ["target_layer"],
];
if(count($val["key"])>0){
for($i=0;$i<count($val["key"]);$i++){
$new["item_id".$i] = $val["key"][$i]["id"];
$new["product_name".$i]=$val["key"][$i]["product_name"];
}
}
array_push($newList,$new);
}
Results:
Array
(
[0] =>Array
(
[id] = > 0 GPHKD
[target_layer] =>Men and women in their teens (T-tier)
[item_id0] = > 10
[product_name0] = > Coffee
[item_id1] =>9
[product_name1] => Coffee mug
)
[1] =>Array
(
[id] = > 0 GPHKC
[target_layer] => Men and women 20-34 years old (M1F1 layer)
[item_id0] = > 10
[product_name0] = > Coffee
[item_id1] =>9
[product_name1] => Coffee mug
)
)
© 2024 OneMinuteCode. All rights reserved.