Reputation: 5585
I've got two foreach()
loops in my php to fetch MySQL data from 2 different dbs.
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"];
}
I want to pass the results from both foreach loops as json_encode()
data.
My question is, how do I pass $number
, $score
and $rank
as json_encode()
?
I tried the below at the bottom of the code, but did not work.
$data = array();
$data[$val] = $val["tel"];
$data[$dta] = $dta["score"];
$data[$dta] = $dta["rnk"];
echo json_encode($data);
Expecting output:
[{"tel":"123456","score":"785","rnk":"135"}]
Upvotes: 1
Views: 214
Reputation: 9103
$dta
and $val
are only in the loops scope. You assign variables within the loop, so use them.
$data = array();
$data['tel'] = $number;
$data['score'] = $score;
$data['rnk'] = $rank;
echo json_encode($data);
You can also assign $data within your foreach loop.
$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);
Upvotes: 1
Reputation: 1968
try this
$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);
Added an extra [] if array size of $val["tel"],$dta["score"],$dta["rnk"]
is greater than 1 else you can remove [] if array size is 1
Upvotes: 0