Jump to content

Is there a better alternative way to reduce the below code?


Go to solution Solved by Barand,

Recommended Posts

<?php
$test['0000'] = ['address' =>'tes0'];
$test['1111'] = ['id'=>'tes1', 'name'=>'tes11', 'address' =>'tes111'];
$test['2222'] = ['id'=>'tes2', 'name'=>'tes22', 'address' =>'tes222'];
$test['3333'] = ['id'=>'tes3', 'name'=>'tes33'];

$keys = [];
foreach ($test as $t) {
    $keys = array_merge($keys, array_keys($t));
}
$keys = array_fill_keys(array_unique($keys), 'NIL');

foreach ($test as &$t) {
    $t = array_merge($keys, $t);
}
print_r($test);

Is there a more better way to reduce the above code to fill in the missing keys and get the expected result as:

Array
(
    [0000] => Array
        (
            [id] => NIL
            [name] => NIL           
            [address] => tes0
        )

    [1111] => Array
        (

            [id] => tes1
            [name] => tes11
            [address] => tes111
        )

    [2222] => Array
        (

            [id] => tes2
            [name] => tes22
            [address] => tes222
           
        )

    [3333] => Array
        (

            [id] => tes3
            [name] => tes33
            [address] => NIL
         
        )

)
 

  • Solution
<?php
$test['0000'] = ['address' =>'tes0'];
$test['1111'] = ['id'=>'tes1', 'name'=>'tes11', 'address' =>'tes111'];
$test['2222'] = ['id'=>'tes2', 'name'=>'tes22', 'address' =>'tes222'];
$test['3333'] = ['id'=>'tes3', 'name'=>'tes33'];

$nil = ['id'=>'NIL', 'name'=>'NIL', 'address' =>'NIL'];

$test = array_map( function($v) use ($nil) {
                      return array_replace($nil, $v);
                   }
                   , $test);

PS Definite feeling of deja vu here

Edited by Barand
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.