Search code examples
phparraysstringimplode

How php array will move to one dimension from two dimensional array


Original array

Array ( [1147183647] => 3 [2147483242] => 1 ) 

expected out put

Array (1147183647,1147183647,1147183647,2147483242)

how can i expand array key base on their value


Solution

  • slightly sexier than those using 2 loops is to use the built in array_fill function

    <?php
    $array = array(1147183647 => 3, 2147483242 => 1);
    
    $new=array();
    foreach ($array as $key=>$var){
    $new= array_merge($new,array_fill(0,$var,$key));
    }
    
    print_r($new);
    

    demo: http://codepad.viper-7.com/NTcDhC