beginnerForPHP Posted April 19, 2022 Share Posted April 19, 2022 <?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 ) ) Quote Link to comment https://forums.phpfreaks.com/topic/314714-is-there-a-better-alternative-way-to-reduce-the-below-code/ Share on other sites More sharing options...
Solution Barand Posted April 19, 2022 Solution Share Posted April 19, 2022 (edited) <?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 April 19, 2022 by Barand Quote Link to comment https://forums.phpfreaks.com/topic/314714-is-there-a-better-alternative-way-to-reduce-the-below-code/#findComment-1595528 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.