Changing the foreach array
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 to something like this:
{
cust_type : Family,
balance : 420946131.01
},
{
cust_type : Regular ,
balance : 41272033223.93
},
and so on..
Here is a simple foreach I used, but it can only print cust_type
orbalance
$cols = array_keys($testing);
foreach ($testing[$cols[1]] as $i => $j) {
echo '{cust_type : ' . $j .
', balance : ' . $<What should I print??> . '},';
}
Please, help. Thank.
source to share
Using array_map (PHP 4> = 4.0.6, PHP 5)
$json = json_encode(array_map(function($a,$b){ return array("cust_type"=>$a,"balance"=>$b);},$array["CUST_TYPE"],$array["TOTAL_BALANCE"]));
Test
[akshay@localhost tmp]$ cat test.php
<?php
$array = array(
"CUST_TYPE" => array(
'Family',
'Regular',
'Corporate',
'Premium'
),
"TOTAL_BALANCE" => array(
420946131.01,
41272033223.93,
38873647942.4 ,
10465337565.61
)
);
// PHP 4,5
$json = json_encode(array_map(function($a,$b){ return array("cust_type"=>$a,"balance"=>$b);},$array["CUST_TYPE"],$array["TOTAL_BALANCE"]),JSON_PRETTY_PRINT);
// Input
print_r($array);
// Output
print $json."\n";
?>
Output
[akshay@localhost tmp]$ php test.php
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
)
)
[
{
"cust_type": "Family",
"balance": 420946131.01
},
{
"cust_type": "Regular",
"balance": 41272033223.93
},
{
"cust_type": "Corporate",
"balance": 38873647942.4
},
{
"cust_type": "Premium",
"balance": 10465337565.61
}
]
source to share
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 another format, you can use array_combine()
creates an array with the first argument as keys and the second as values,
The format you specify, json
So, json_encode()
will do it for you,
$required = array_combine($your_array['CUST_TYPE'], $your_array['TOTAL_BALANCE']);
$required = json_encode($required);
Now $required
- the string with the required value. What is,
{"Family":420946131.01,"Regular":41272033223.93,"Corporate":38873647942.4,"Premium":10465337565.61}
Note. Make sure you have the same number of elements in the arrays $your_array['CUST_TYPE']
and $your_array['TOTAL_BALANCE']
inside your input array. Otherwise, you will see a warning.
source to share