Jump to content

How to pre fill an array with missings keys?


Go to solution Solved by Barand,

Recommended Posts

$test['0000'] = [2 =>'tes000'];

$test['1111'] = [0=>'tes1', 1=>'tes11', 2 =>'tes111'];

$test['2222'] = [0=>'tes2', 1=>'tes22', 2 =>'tes333'];

How do i prefill the $test array with missing keys  with value as 'NIL' to get the result as :

$test['0000'] = [0=>'NIL', 1=>'NIL', 2 =>'tes000'];

$test['1111'] = [0=>'tes1', 1=>'tes11', 2 =>'tes111'];

$test['2222'] = [0=>'tes2', 1=>'tes22', 2 =>'tes333'];

 

  • Solution
$test =  [ '0000' => [2 =>'tes000'],
           '1111' => [0=>'tes1', 1=>'tes11', 2 =>'tes111'],
           '2222' => [0=>'tes2', 2 =>'tes333']
         ] ;
         
$test = array_map( function($v) {
                      return array_replace(array_fill_keys(range(0,2), 'NIL'), $v);
                   }
                   , $test);
                   
echo '<pre>' . print_r($test, 1) . '</pre>';

giving

Array
(
    [0000] => Array
        (
            [0] => NIL
            [1] => NIL
            [2] => tes000
        )

    [1111] => Array
        (
            [0] => tes1
            [1] => tes11
            [2] => tes111
        )

    [2222] => Array
        (
            [0] => tes2
            [1] => NIL
            [2] => tes333
        )

)

 

  • Like 1

@BarandHow do i use the range() in case if my array is as follows with time range  or is there any other alternative as time difference can be based on hour and half-hour. In example it is based on every hour.

 

Screenshot 2022-04-15 at 09.40.29.png

Edited by beginnerForPHP

Use a DatePeriod() object to generate the NIL array.

I'd show the code but I am having difficulty processing that image of your data in my test code.

(Hint: in future, use var_export() with arrays)

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.