[英]Getting values from JSONarray
I am writing a PHP script which我正在写一个 PHP 脚本
connects to the database连接到数据库
fetches all orders in an array.获取数组中的所有订单。 ($result)
($结果)
I want to go through the array and fetch all say "userName"我想遍历数组并获取所有说“用户名”
The trouble is, with my code below, I am able to only get the first character of each "userName" in the array.I want an array with all "userName"s.问题是,使用下面的代码,我只能获取数组中每个“userName”的第一个字符。我想要一个包含所有“userName”的数组。
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$dbname = 'dbname';
//Create database connection
$dblink = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = "select * from ordertest";
$retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));
$result = mysqli_fetch_array($retval, MYSQLI_ASSOC);
if (mysqli_num_rows($retval) > 0) {
$arr = json_decode($result, true);
foreach ($result as $key => $value) {
echo $value["userName"];
}
} else {
echo $sql;
}
The solution should be next:解决方案应该是下一个:
<?php
$sql = "select * from ordertest";
// retrieve query result from DB
$retval = mysqli_query($dblink, $sql) or die(mysqli_error($dblink));
// if result not empty
if (mysqli_num_rows($retval) > 0) {
// retrieve single row from $retval
while ($result = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo $result["userName"];
echo "\n";
}
} else {
echo $sql;
}
Look example here: PHPize.online看看这里的例子: PHPize.online
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.