phparrayscakephp-3.0transposedefault-value

Transpose 2d array's associative array elements containing indexed rows of differing counts and enforce custom default values


How can I convert input array

$input['id'] = [1,2,3,4];
$input['name'] = ['a' , 'b' , 'c'];
$input['alias'] = ['i' , 'ii' , 'iii' , 'iv' , 'v'];
$input['object'] = [$object1 , $object2];

to output array

$output[] = ['id'=>1 , 'name'=>'a' , 'alias'=>'i' , 'object'=>$object1];
$output[] = ['id'=>2 , 'name'=>'b' , 'alias'=>'ii' , 'object'=>$object2];
$output[] = ['id'=>3 , 'name'=>'c' , 'alias'=>'iii' , 'object'=>NULL];
$output[] = ['id'=>4 , 'name'=>'' , 'alias'=>'iv' , 'object'=>NULL];
$output[] = ['id'=>0 , 'name'=>'' , 'alias'=>'v' , 'object'=>NULL];

missed number = 0
missed string = ''
missed object = null


Solution

  • As a first answer, i would do the following :

    $output = array_map(null, $input['id'], $input['name'], $input['alias'], $input['object']);

    This will create an array from your arrays.

    Counterpart of this solution is that it always return null if value is not set.

    More info : http://php.net/manual/en/function.array-map.php#example-5583


    EDIT 03 May 2017 If you need to add the keys to the output (id, name, alias, object), you could apply a function to each item in the stack to add them. The following is a possible solution :

    array_walk($output, function(&$item, $key) { $item = array_combine(['id','name','alias', 'object'], array_values($item)); });