Php 将中的数组转换为另一个数组
在我的项目中,我有以下类型的数组。请帮助我找到解决方案。 下面给出了数组,请参考。 看起来是这样的Php 将中的数组转换为另一个数组,php,arrays,multidimensional-array,shuffle,Php,Arrays,Multidimensional Array,Shuffle,在我的项目中,我有以下类型的数组。请帮助我找到解决方案。 下面给出了数组,请参考。 看起来是这样的 [0] => Array ( [Notification] => Array ( [id] => 135 [notification_date] => 2013-09-18 [short_desc] =
[0] => Array
(
[Notification] => Array
(
[id] => 135
[notification_date] => 2013-09-18
[short_desc] => dsfdfdfdf
[long_desc] =>
)
[NotificationProduct] => Array
(
[0] => Array
(
[id] => 41
[notification_id] => 135
[product_id] => 20
[Product] => Array
(
[id] => 20
[category_id] => 2
[name] => asasasa
)
)
[1] => Array
(
[id] => 42
[notification_id] => 135
[product_id] => 21
[Product] => Array
(
[id] => 21
[category_id] => 2
[name] => corn flakcf
)
)
)
)
我有上述类型的数组。现在我想将其转换为以下方式:
[0] => Array
(
[Notification] => Array
(
[id] => 135
[notification_date] => 2013-09-18
[short_desc] => dsfdfdfdf
[long_desc] =>
)
[NotificationProduct] => Array
(
[0] => Array
(
[id] => 41
[notification_id] => 135
[product_id] => 20
[name] => asasasa
)
[1] => Array
(
[id] => 42
[notification_id] => 135
[product_id] => 21
[name] => corn flakcf
)
)
)
Is there any way to convert it into that kind of array.
谢谢
$name = $array[0]['NotificationProduct'][0]['product']['name']
unset($array[0]['NotificationProduct'][0]['product'])
$array[0]['NotificationProduct'][0]['name'] = $name;
对$array[0]['NotificationProduct'][1]['product']执行相同的操作尝试以下操作:
$counter = 0;
$responseArray = array();
foreach($notifications as $notification){
$responseArray[$counter]['Notification'] = $notification['Notification'];
$counter1 = 0;
foreach($notification['NotificationProduct'] as $notificationProduct){
$responseArray[$counter]['NotificationProduct'][$counter1]['product_id'] = $notificationProduct['product_id'];
$responseArray[$counter]['NotificationProduct'][$counter1]['product_name'] = $notificationProduct['Product']['name'];
$responseArray[$counter]['NotificationProduct'][$counter1]['product_desc'] = $notificationProduct['Product']['description'];
$counter1++;
}
$counter++;
}
假设您的数组是name$notices
,请尝试以下操作:
foreach($notices AS $key => $val )
{
if($key=='NotificationProduct')
{
foreach($val AS $idx => $np )
{
$notices[$key][$idx]['name'] = $notices[$key][$idx]['Product']['name'];
unset($notices[$key][$idx]['Product']);
}
}
}
你应该展示你的方法有一种方法:你通过原始数组循环,修改它以匹配你想要的结构你的根数组有数字索引吗?如果是这样,请尝试使用$array[0]
而不是$array
。我已经测试了代码,它正在为我工作。是否可以使用foreach循环?更新了答案。是,也可以使用foreach
循环。父数组包含数字索引