选择的值为json_encode数据

时间:2015-06-25 07:34:47

标签: php mysql json

我的php中有两个foreach()循环来从两个不同的dbs中获取MySQL数据。

foreach ($result as $val) {
   $country = $val["count"]; //results fetched successfully
   $number = $val["tel"];
}

foreach ($rslt as $dta) {
   $score = $dta["score"]; //results fetched successfully
   $rank = $dta["rnk"];
}

我想将两个foreach循环的结果作为json_encode()数据传递。 我的问题是,如何将$number$score$rank作为json_encode()传递?

我在代码底部尝试了以下内容,但没有用。

$data = array();
$data[$val] = $val["tel"];
$data[$dta] = $dta["score"];
$data[$dta] = $dta["rnk"];
echo json_encode($data);

期待输出:

[{"tel":"123456","score":"785","rnk":"135"}]

2 个答案:

答案 0 :(得分:1)

$dta$val仅在循环范围内。您在循环中分配变量,因此请使用它们。

$data = array();
$data['tel'] = $number;
$data['score'] = $score;
$data['rnk'] = $rank;
echo json_encode($data);

您还可以在foreach循环中分配$ data。

$data = array();

foreach ($result as $val) {
   $data['country'] = $val["count"]; //results fetched successfully
   $data['tel'] = $val["tel"];
}

foreach ($rslt as $dta) {
   $data['score']= $dta["score"]; //results fetched successfully
   $data['rank'] = $dta["rnk"];
}

echo json_encode($data);

答案 1 :(得分:0)

试试这个

$data = array();
foreach ($result as $val) {
   $data['tel'][] = $val["tel"];
   $country = $val["count"]; //results fetched successfully
   $number = $val["tel"];
}

foreach ($rslt as $dta) {
   $data['score'][] = $dta["score"];
   $data['rnk'][] = $dta["rnk"];
   $score = $dta["score"]; //results fetched successfully
   $rank = $dta["rnk"];
}

echo json_encode($data);

如果$val["tel"],$dta["score"],$dta["rnk"]的数组大小大于1,则添加额外的[]如果数组大小为1,则可以删除[]