我正在尝试将数组转换为json,但没有得到我想要的确切结果。
在这里
<?php
$result=array();
$result[status]=1;
$data=array(
array("ucode" => "123","name" => "abc","lname" => "xyz"),
array("ucode" => "431","name" => "cdb","lname" => "zsa")
);
foreach($data as $res){
$data=array();
$data[ucode]=$res['ucode'];
$data[name]= $res['name'];
$data[lname]= $res['lname'];
$result[content]=$data;
}
echo $res=json_encode($result);
?>
实际结果:
{"status":1,"content":{"ucode":"431","name":"cdb","lname":"zsa"}}
我的预期结果:
{"status":1,"content":[{"ucode":"123","name":"abc","lname":"xyz"},{"ucode":"431","name":"cdb","lname":"zsa"}]}
请指导我哪里出错了,没有得到预期的结果。
答案 0 :(得分:6)
为什么需要循环,如果您可以直接将数据推入结果的内容索引中。
$result = [];
$result["status"] = 1;
$data = [
["ucode" => "123", "name" => "abc", "lname" => "xyz"],
["ucode" => "431", "name" => "cdb", "lname" => "zsa"],
];
$result['content'] = $data;
echo $res = json_encode($result);
简短形式
$result = ['status' => 1, 'content' => $data];
echo json_encode($result);
工作demo。
输出
{"status":1,"content":[{"ucode":"123","name":"abc","lname":"xyz"},
{"ucode":"431","name":"cdb","lname":"zsa"}]}
答案 1 :(得分:2)
您重用变量$data
会导致问题。同样,当您追加到$result['content']
数组时,也需要使用[]
。
<?php
$result = array(
'content' => array(),
'status' => 1
);
$data= array(
array("ucode" => "123","name" => "abc","lname" => "xyz"),
array("ucode" => "431","name" => "cdb","lname" => "zsa")
);
foreach($data as $res){
$tmp = array(
'ucode' => $res['ucode'],
'name' => $res['name'],
'lname' => $res['lname']
);
$result['content'][] = $tmp;
}
echo $res = json_encode($result);
?>
答案 2 :(得分:0)
我还有另一种解决方法,就是和你们一起
因为当我使用json_encode()传入api时,我想重命名变量名称。
<?php
$result=array();
$result['status']=1;
$data=array(
array("ucode" => "123","name" => "abc","lname" => "xyz"),
array("ucode" => "431","name" => "cdb","lname" => "zsa"),
);
$ar=array();
foreach($data as $res){
$data=array();
$data['u_code']=$res['ucode'];
$data['u_name']= $res['name'];
$data['u_lname']= $res['lname'];
$ar[]=$data;
}
$result['content']=$ar;
echo $res=json_encode($result);
?>