Skip to content
Advertisement

Create Array From Key

Thank you in advance. Is there any way to create a multidimensional array from key names.

$array = array(
    'brand/name' => 'BRAND_NAME',
    'brand/model' => 'MODEL_NO',
    'brand/inv/qty' => '20',
    'brand/inv/cost' => '30',
    'wh' => 'NY',
    'brand/inv/sales' => '40'
);

Transform to this array.

$array = array(
    'brand' => array(
        'name' => 'BRAND_NAME',
        'model' => 'MODEL_NO',
        'inv' => array(
            'qty' => 20,
            'cost' => 30,
            'sales' => 40,
        )
    ),
    'wh' => 'NY'
);

Thank you !

Advertisement

Answer

Try my code (I used the reference operator “&” to get the successive inner arrays):

Input array:

$array = array(
        'brand/name' => 'BRAND_NAME',
        'brand/model' => 'MODEL_NO',
        'brand/inv/qty' => '20',
        'brand/inv/cost' => '30',
        'wh' => 'NY',
        'brand/inv/sales' => '40'
);

php code:

<?php

$resultArray = array();

foreach($array as $path => $element) {
    $pathArray = explode("/", $path);

    $auxRef = &$resultArray;

    foreach($pathArray as $pathPart) {
        if(! array_key_exists($pathPart, $auxRef)) {
            $auxRef[$pathPart] = array();
        }

        $auxRef = &$auxRef[$pathPart];
    }

    $auxRef = $element;
    unset($auxRef);
}
?>

Result array:

array ( 'brand' => array ( 'name' => 'BRAND_NAME', 'model' => 'MODEL_NO', 'inv' => array ( 'qty' => '20', 'cost' => '30', 'sales' => '40', ), ), 'wh' => 'NY', )

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement