我正在尝试遍历我发布到PHP后端的JSON。 JSON看起来像这样:
UPDATE UserAnswer
SET userId = (SELECT TOP(1) id FROM Users Order By id DESC)
WHERE userId = NULL
我是这样从邮差发布的:
我希望能够使用
打印我单独发布的每个号码[
{
"number":"5613106"
},
{
"number":"56131064"
},
{
"number":"56131063"
}
]
现在,当我使用以下内容时,它只打印最后一个数字:
echo $number;
我的功能:
$number = $json['number'];
echo $number;
输出:
public function check_users_post()
{
$json = $this->request->body;
print_r($json);
$this->response($json, REST_Controller::HTTP_OK);
}
答案 0 :(得分:2)
希望这个通用迭代器能帮到你。
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
答案 1 :(得分:1)
使用
json_decode()
PHP内置函数,用于将json解码回PHP变量或数组,然后遍历每个索引并打印数字。
答案 2 :(得分:1)
这样做:
public function check_users_post()
{
$json = $this->request->body;
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($json),
RecursiveIteratorIterator::SELF_FIRST);
$phone_numbers = "";
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
} else {
$phone_numbers = "$phone_numbers" . ", " . "$val";
}
}
$phone_numbers = substr($phone_numbers, 2);
$phone_numbers = "(" . $phone_numbers . ")";
$query = $this->db->query("SELECT * FROM users WHERE user_number in $phone_numbers;");
$result = $query->result();
$this->response($result, REST_Controller::HTTP_OK);
if (mysql_num_rows($result)==0) {
$data = [ 'message' => 'No users returned'];
$this->response($data, REST_Controller::HTTP_BAD_REQUEST);
} else {
$this->response($result, REST_Controller::HTTP_OK);
}
}
答案 3 :(得分:0)
<强>描述强>
首先对你的JSON进行字符串化,而不是使用JSON_DECODE()函数,该函数为你提供数组,然后使用foreach循环对这个数组进行迭代,这将为你提供你想要回应的每个键。
<强>代码强>
$str = '[
{
"number":"5613106"
},
{
"number":"56131064"
},
{
"number":"56131063"
}
]';
$array = json_decode($str, true);
echo "<pre>";
foreach ($array as $key => $key_value) { // then loop through it
echo "<br>";
echo $array[$key]['number'];
echo "<br>";
}
<强>输出强>
5613106
56131064
56131063