我有一个像这样的数组$testing
:
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
},
and so on..
以下是我使用的简单foreach,但它只能打印cust_type
或balance
$cols = array_keys($testing);
foreach ($testing[$cols[1]] as $i => $j) {
echo '{cust_type : ' . $j .
', balance : ' . $<What should I print??> . '},';
}
请帮助。 谢谢。
答案 0 :(得分:3)
考虑这个片段,
$scope.showMe=function(){
$scope.isVisible=!$scope.isVisible;
}
将输出,
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);
对于其他格式,您可以使用array_combine()
创建一个数组,其中第一个参数作为键,第二个作为值,
您指定的格式为[{"cust_type":"Family","balance":420946131.01},{"cust_type":"Regular","balance":41272033223.93},{"cust_type":"Corporate","balance":38873647942.4},{"cust_type":"Premium","balance":10465337565.61}]
因此,json
会为您执行此操作,
json_encode()
现在,$required = array_combine($your_array['CUST_TYPE'], $your_array['TOTAL_BALANCE']);
$required = json_encode($required);
是您想要的值的字符串。是的,
$required
注意:确保输入数组中的{"Family":420946131.01,"Regular":41272033223.93,"Corporate":38873647942.4,"Premium":10465337565.61}
和$your_array['CUST_TYPE']
数组中的成员数相同。否则你会看到警告。
答案 1 :(得分:1)
使用array_map(PHP 4&gt; = 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"]));
<强>测试强>
[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";
?>
<强>输出强>
[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
}
]