mitra razmara
mitra razmara

Reputation: 791

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

Upvotes: -1

Views: 100

Answers (2)

mickmackusa
mickmackusa

Reputation: 48031

Transposing the data with array_map() will eliminate the need to manually count the number of iterations required. To tidy up the preferred default values when missing, use the null coalescing assignment operator before returning the new associative row on each iteration.

Code: (Demo)

var_export(
    array_map(
        function(?int $id, ?string $name, ?string $alias, ?object $object) {
            $id ??= 0;
            $name ??= '';
            $alias ??= '';
            return get_defined_vars();    
        },
        $input['id'],
        $input['name'],
        $input['alias'],
        $input['object']
    )
);

Output:

array (
  0 => 
  array (
    'id' => 1,
    'name' => 'a',
    'alias' => 'i',
    'object' => 
    (object) array(
       'foo' => 1,
    ),
  ),
  1 => 
  array (
    'id' => 2,
    'name' => 'b',
    'alias' => 'ii',
    'object' => 
    (object) array(
       'bar' => 2,
    ),
  ),
  2 => 
  array (
    'id' => 3,
    'name' => 'c',
    'alias' => 'iii',
    'object' => NULL,
  ),
  3 => 
  array (
    'id' => 4,
    'name' => '',
    'alias' => 'iv',
    'object' => NULL,
  ),
  4 => 
  array (
    'id' => 0,
    'name' => '',
    'alias' => 'v',
    'object' => NULL,
  ),
)

Upvotes: 0

Guillaume
Guillaume

Reputation: 581

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)); });

Upvotes: 0

Related Questions