skip to Main Content
array(
    array(
    'drive'=>array('test1'),
    'wheel_drive'=>array('2WD','4WD')
    ),
    array(
        0=>array(
            'drive'=>array('test21','test31'),
            'wheel_drive'=>array('2WD','4WD')
        ),
        1=>array(
            'drive'=>array('test32'),
            'wheel_drive' => array('4WD')
        )
    ),
    array(
        'drive' => array('test4'),
        'wheel_drive'=> array('2WD','4WD')
    )
);

Output:

array(
    array('drive'=>array('test1'),'wheel_drive'=>array('2WD','4WD')),
    array('drive'=>array('test21','test31'),'wheel_drive'=>array('2WD','4WD')),
    array('drive'=> array('test32'),'wheel_drive' => array('4WD')),
    array('drive' => array('test4'),'wheel_drive'=> array('2WD','4WD'))
);

How can we get child array out of main array and then merge it into parent array as its node.

    function flattenArray($key, $array) {
    $result = array();
    foreach ($array as $k=> $element) {
        if (is_array($element)) {
            $result = array_merge($result, flattenArray($k, $element));
        } else {
            $result[$key][] = $element;
        }
    }

    return $result;
}

$outputArray = array();

foreach ($inputArray as $key=> $item) {
    $outputArray[] = flattenArray($key, $item);
}

print_r($outputArray);

I have this array in which I am trying to extract sub-array and merge into main array so that my result would be like this
one array with all child array with save depth.

2

Answers


  1. With a slight modification to your code you can extract the array you want:

    $outputArray = array();
    
    function flattenArray(&$output, $input)
    {
        foreach ($input as $key=> $item) {
            if (in_array('drive', array_keys($item))) {
                $output[] = $item;
            } else {
                flattenArray($output, $item);
            }   
        }    
    }
    
    flattenArray($outputArray, $inputArray);
    
    print_r($outputArray);
    

    See: https://3v4l.org/Ut27X

    That being said: The data array doesn’t make sense. I think it would be better to work on the code that generates this data array. Prevent the problem from occurring in the first place.

    Login or Signup to reply.
  2. $input = [
      [ 'drive' => [ 'test1' ], 'wheel_drive' => [ '2WD', '4WD' ] ],
      [
        [ 'drive' => [ 'test21', 'test31' ], 'wheel_drive' => [ '2WD', '4WD' ] ],
        [ 'drive' => [ 'test32' ], 'wheel_drive' => [ '4WD' ] ]
      ],
      [ 'drive' => [ 'test4' ], 'wheel_drive' => [ '2WD', '4WD' ] ]
    ];
    
    $result = array_reduce(
      $input,
      static fn($carry, $item) => array_merge($carry, array_is_list($item) ? $item : [ $item ]),
      []
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search