我需要遍历一个多维数组,并将数组中类型为array的每个元素包装在一个数组中。
示例数组:
Array
(
[product_id] => 1
[product_name] => Jack Daniel's
[sku] => 0
[size] => 700
[case_size] => 6
[description] => A spirit from USA
[status] => ACTIVE
[created] => 2016-10-02 23:13:17
[modified] => 2016-10-02 23:13:17
[packs] => Array
(
[product_pack_id] => 1
[store_id] => 1
[product_id] => 1
[pack_size] => 1
[created] => 2016-10-02 23:13:17
[modified] => 2016-10-02 23:13:17
[barcodes] => Array
(
[product_barcode_id] => 1
[product_id] => 1
[store_id] => 1
[product_pack_id] => 1
[barcode] => 82184045954
[created] => 2016-09-29 06:48:54
[modified] => 2016-09-29 06:48:54
)
)
)
但是阵列的深度可以从3个深度变为无限深。
我需要将每个n深度包装在一个数组中,例如packs =>需要包装在一个数组中,但也包装=>条形码需要包装在一个数组中,以便得到以下结果:
Array
(
[product_id] => 1
[product_name] => Jack Daniel's 700ml
[sku] => 0
[size] => 700
[case_size] => 6
[description] =>
<p>Jack Daniel's is a sour mash charcoal filtered American whiskey, which makes it different to it cousin, Bourbon. The mash is made up of 80% corn, 12% rye and 8% malt. Then filtered through 10 feet of charcoal to mellow out the flavours of the malt and the corn, which gives it a distinctive smoky flavour.</p>
[status] => ACTIVE
[created] => 2016-10-02 23:13:17
[modified] => 2016-10-02 23:13:17
[packs] =>
[0] => Array
(
[product_pack_id] => 1
[store_id] => 1
[product_id] => 1
[pack_size] => 1
[created] => 2016-10-02 23:13:17
[modified] => 2016-10-02 23:13:17
[barcodes] =>
[0] => Array
(
[product_barcode_id] => 1
[product_id] => 1
[store_id] => 1
[product_pack_id] => 1
[barcode] => 82184045954
[created] => 2016-09-29 06:48:54
[modified] => 2016-09-29 06:48:54
)
)
)
但是数组的深度是可变的,例如上面的深度为3,但明天可能会增加到4的深度。
答案 0 :(得分:1)
使用递归很容易解决。下面未经测试的代码,但这应该给你一个好主意。
function wrapArrays($array) {
$wrappedArray = array();
foreach($array as $k => $v) {
if(is_array($v)) $wrappedArray[$k] = array(wrapArrays($v));
else $wrappedArray[$k] = $v;
}
return $wrappedArray;
}
这里的想法是遍历数组的第一级,如果任何元素是数组,则以相同的方式遍历该数组,并继续前进,直到每个级别的每个元素都被处理,无论如何数组的深度是。
答案 1 :(得分:-2)
遵循机制。
<?php
$result = array();
while(data available){ // loop for getting all available data
$result['product_id'] = 'value';
$result['product_name'] = 'value';
$result['sku'] = 'value';
.
.
.
.
.
.
$result['packs'][]['product_pack_id'] = 'value';
$result['packs'][]['store_id'] = 'value';
$result['packs'][]['product_id'] = 'value';
.
.
.
.
$result['packs'][]['barcodes'][]['product_barcode_id'] = 'value';
$result['packs'][]['barcodes'][]['product_id'] = 'value';
.
.
.
.
}
print_r($result);
?>