Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array foreach modification

I have an array $testing like this :

Array ( 
    [CUST_TYPE] => 
        Array ( 
            [0] => Family 
            [1] => Regular 
            [2] => Corporate 
            [3] => Premium ) 
    [TOTAL_BALANCE] => 
        Array ( 
            [0] => 420946131.01 
            [1] => 41272033223.93 
            [2] => 38873647942.4 
            [3] => 10465337565.61 ) 
        )

I need to convert (print) this array into something like this :

{
cust_type : Family,
balance : 420946131.01
},
{
cust_type : Regular ,
balance : 41272033223.93
},
and so on..

Here is simple foreach that I used, but it can only print cust_type or balance

$cols = array_keys($testing);

foreach ($testing[$cols[1]] as $i => $j) {
        echo '{cust_type : ' . $j . 
             ', balance : ' . $<What should I print??> . '},';        
    }

Kindly please to help. Thank you.

like image 598
King Goeks Avatar asked Nov 18 '25 08:11

King Goeks


1 Answers

Consider this snippet,

for($i=0; $i<count($your_array['CUST_TYPE']); $i++)
{
    $required[] = [ 'cust_type' => $your_array['CUST_TYPE'][$i],
                    'balance' => $your_array['TOTAL_BALANCE'][$i] ];
}

$required = json_encode($required);

will output,

[{"cust_type":"Family","balance":420946131.01},{"cust_type":"Regular","balance":41272033223.93},{"cust_type":"Corporate","balance":38873647942.4},{"cust_type":"Premium","balance":10465337565.61}]

For other format, You can use array_combine() creates an array with first argument as keys and second as values,

The format you are specifying is json So, json_encode() will do that for you,

$required = array_combine($your_array['CUST_TYPE'], $your_array['TOTAL_BALANCE']); 

$required = json_encode($required);

Now, $required is string with your desired value. Which is,

{"Family":420946131.01,"Regular":41272033223.93,"Corporate":38873647942.4,"Premium":10465337565.61}

Note: Make sure you have same number of members in both $your_array['CUST_TYPE'] and $your_array['TOTAL_BALANCE'] arrays inside your input array. Otherwise you will see a warning.

like image 173
viral Avatar answered Nov 19 '25 23:11

viral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!