简体   繁体   English

PHP创建JSON数组数组(来自MySQL的数据)

[英]PHP Creating JSON array of arrays (data coming from MySQL)

i've been searching all over and can't get any solution to work... this is my code, the problematic area is how to create 1 large array of per-sql-row array: (the commented-out line is the one causing the error). 我一直在搜索,无法获得任何解决方案......这是我的代码,问题在于如何创建1个大型的每个sql行数组:(注释掉的行是一个导致错误)。

$result = mysqli_query($con, "SELECT * FROM  `Orders` WHERE  `userID` = " . $objData->userid . " ORDER BY  `recievedDate` DESC LIMIT 10");
        $resArray = array();    
        if ($result->num_rows > 0) {
            while($row = $result->fetch_row())
            {
                $tempArr = array("orderid" => $row[0], "orderdate" => $row[2], "orderstatus" => $row[4]);
                //$resArray = array_push((array)$resArray, (array)$tempArr);  <== problematic line commented out
            }
            echo json_encode($resArray);        
        } else {                
            echo "";    
        }

thanks! 谢谢!

除了其他重要方面,你$resArray = array_push((array)$resArray, (array)$tempArr)分配array_push $resArray = array_push((array)$resArray, (array)$tempArr) ,所以json_encode($resArray)得到一个数字而不是你需要的数组。

The simple answer is to push your $temparr array to $resArray like this: 简单的答案是将$temparr数组推送到$resArray如下所示:

$resArray[] = $tempArr;

Note you could also use array_push() if you really wanted to. 请注意,如果你真的想要,你也可以使用array_push()

Not sure what all your query is returning, but did you know you could also just get your query results as an array to begin with? 不知道你的所有查询都返回了什么,但是你知道你也可以将你的查询结果作为一个数组开始吗?

$resArray = $result->fetch_array(MYSQLI_ASSOC);

If your query is returning more than you need in your array, just limit the query: 如果您的查询返回的数量超过了数组中的需要,则只需限制查询:

$result = mysqli_query($con, "SELECT orderid, orderdate, orderstatus FROM  `Orders` ...");
$resArray = $result->fetch_array(MYSQLI_ASSOC);

Done! 完成!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM