skip to Main Content

I have a multidimensional array like

$inputArray = array(
    array(
        array('value31', 'value32'),
        array('value33', 'value34'),
        'value21'
    ),
    'value11'
);

I need to pop the last item from each item and considered it as the key for rest values. Output array should like,

$outputArray = array(
    'value11' => array(
        'value21' => array(
            array('value31', 'value32'),
            array('value33', 'value34'),
        )
    )
);

I tried this code, but it doesn’t work.

function convertArray(array $inputArray, $old_key = null) {
    $outputArray = [];
    $isMultiDimensional = count($inputArray) != count($inputArray, COUNT_RECURSIVE);
    $array_key = $isMultiDimensional ? array_pop($inputArray) : $old_key;

    foreach ($inputArray as $value) {
        $itemIsMultiDimensional = count($value) != count($value, COUNT_RECURSIVE);

        if (is_array($value) && $itemIsMultiDimensional) {
            $outputArray = array_merge($outputArray, convertArray($value, $array_key));
        } else {
            $outputArray[$array_key][] = $value;
        }
    }

    return $outputArray;
}

2

Answers


  1. function convertArray(array $inputArray) {
        $lastItem = array_pop($inputArray);
        $outputArray = [];
        if (!empty($inputArray) && is_array($lastItem)) {
            $outputArray = convertArray($inputArray);
            $outputArray[$lastItem[0]] = $lastItem[1];
        } else {
            $outputArray[$lastItem] = $inputArray;
        }
    
        return $outputArray;
    }
    
    $inputArray = array(
        array(
            array('value31', 'value32'),
            array('value33', 'value34'),
            'value21'
        ),
        'value11'
    );
    
    $outputArray = convertArray($inputArray);
    print_r($outputArray);
    
    Login or Signup to reply.
  2. In your foreach change the if and check

    if (is_array($value) && $itemIsMultiDimensional) {
        $outputArray[$array_key] = convertArray($value, $array_key);
    } else {
        $outputArray[$array_key] = $value;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search