joshualawson joshualawson - 24 days ago 6
PHP Question

Walk array with dynamic depth

I need to walk through a multidimensional array and wrap each element that is of type array in an array.

example 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
)

)

)


But the depth of the array can change from 3 arrays deep to unlimited.

I need to wrap each n depth in an array, for example packs => needs to be wrapped in an array but also packs => barcodes needs to be wrapped in an array to give me the following result:

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&nbsp;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
)

)

)


But the depth of the array is variable, for instance the above has a depth of 3 but it could grow to a depth of 4 tomorrow.

Answer

Pretty easily solved with recursion. Untested code below, but this should give you a good idea.

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;
}

The idea here is to go through the first level of your array, and if any elements are arrays, go through that array in the same way, and keep going and going until every element at every level is processed, no matter how deep the array is.