-1

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 !

1

1 Answer 1

1

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', )

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.