我想以JSON格式显示数据
我想以JSON格式显示if和else语句数据
foreach($share_amount as $value)
{
if($value<$total_avg){
$a= $total_avg-$value;
$data2['pay_amount'] = $a;
$data2['member_id'] = $detail;
$data2['contribution_response'] = "Need to pay";
}
else
{
$b= $total_avg-$value; /* the share amount stored and calculated*/
....
$data2['contribution_response'] = "Need to take";
}
echo json_encode(array($data2));
/*storing in json but not getting displayed in the format*/
答案 0 :(得分:0)
json_encode()示例并使用JSON_FORCE_OBJECT:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr,JSON_FORCE_OBJECT);
?>
根据您的代码
## I want to display the data in json format ##
$data2 = array();
foreach($share_amount as $value)
{
if($value<$total_avg){
$a= $total_avg-$value;
$data2['pay_amount'] = $a;
$data2['member_id'] = $detail;
$data2['contribution_response'] = "Need to pay";
}
else
{
$b= $total_avg-$value; /* the share amount stored and calculated*/
$data2['contribution_response'] = "Need to take";
}
}
echo json_encode($data2, JSON_FORCE_OBJECT); /*storing in json but not getting displayed in the format*/
答案 1 :(得分:0)
您的代码中有一个array()
类型变量,它总是重新分配给特定值,尝试使用[]
为新数组值进行自动分区。
$data2 = array();
foreach($share_amount as $value)
{
$tmp_array = array();
if($value < $total_avg){
$a= $total_avg - $value;
$tmp_array['pay_amount'] = $a;
$tmp_array['member_id'] = $detail;
$tmp_array['contribution_response'] = "Need to pay";
}
else
{
$b = $total_avg - $value; /* the share amount stored and calculated*/
$tmp_array['contribution_response']= "Need to take";
}
$data2[]['anytime'] = $tmp_array;
}
echo json_encode($data2);
答案 2 :(得分:0)
您需要构建一个数组数组 - 对于循环中的每次迭代,您需要将结果作为数组添加到输出对象($payload
),然后在结束时对其进行编码。
$payload=array();
foreach($share_amount as $value){
$data=array();
if( $value < $total_avg ){
$a=$total_avg-$value;
$data['pay_amount'] = $a;
$data['member_id'] = $detail;
$data['contribution_response'] = "Need to pay";
$payload[]=$data;
} else {
$b=$total_avg-$value;
$data['pay_amount']=$b;
$data['member_id'] = '';
$data['contribution_response']="Need to take";
}
}
echo json_encode( $payload );
答案 3 :(得分:-1)
This is how I got the answer
foreach($share_amount as $value)
{
if($value<$total_avg){
$a= $total_avg-$value;
$data2['pay_amount'] = $a;
$data2['member_id'] = $detail;
$data2['contribution_response'] = "Need to pay";
}
else
{
$b= $total_avg-$value;
$edata['pay_amount'] = $b;
$edata['member_id'] = $detail;
$edata['contribution_response'] = "Need to take";
//echo json_encode($data2);
}
echo "\n";
}
echo json_encode(array($data2,$edata));