固定的期望数组,但有对象代替?

时间:2019-05-08 08:41:29

标签: php angularjs

我正在尝试使用我的API来显示数据库中的数据,但出现此错误:

"Expected array but received: {"data":{"useri":[{"ID":"1","username":"asdas","city":"asdasd","age":"20"},"

如何做到这一点,所以我只能获得以ID:1开头的数组?

PHP:

if($num > 0){
        $users_array = array(); //stocam userii intr-un array
        $users_array['useri'] = array();

        while($num = $rdej->fetch(PDO::FETCH_ASSOC)){
            extract($num);

            $users_item = array(
                "ID" => $ID,
                "username" => $username,
                "city" => $city,
                "age" => $age
            );

            array_push($users_array['useri'], $users_item);


        }

        // 200 OK - request reusit
        http_response_code(200);

        echo json_encode($users_array);

JS:

crud.controller("DbController",['$scope','$http', function($scope,$http){


    getInfo();
        function getInfo(){

        $http.post('http://vladmaican.dev.ascensys.ro/first/api/users/read.php').then(function(data){
        // Stored the returned data into scope
        $scope.users = data;
            });
        }
}]);

如何做到这一点,所以我只能获得以ID:1开头的数组?

另外,html:

<tr ng-repeat="user in users| filter:search_query">
            <td>
            <span>{{user.username}}</span></td>
            <td>{{user.city}}</td>
            <td>{{user.age}}</td>
            <td>
</tr>

2 个答案:

答案 0 :(得分:0)

当您将“ useri”作为索引时,json_encode输出始终是一个json对象。

要输出json数组,要编码的数组应该只是索引数组。

$indexed_array = array($user1, $user2);

$associative_array = array("user1" => $user1, "user2" => $user2);

所以您可以这样做

if($num > 0){
    $users_array = array(); //stocam userii intr-un array

    while($num = $rdej->fetch(PDO::FETCH_ASSOC)){
        extract($num);

        $users_item = array(
            "ID" => $ID,
            "username" => $username,
            "city" => $city,
            "age" => $age
        );

        array_push($users_array, $users_item);


    }

    // 200 OK - request reusit
    http_response_code(200);

    echo json_encode($users_array);
}

如果需要引用useri,则可以在客户端的javasript中进行引用

答案 1 :(得分:0)

正在创建额外信息的是您的代码,因此只需停止添加您不想要的子数组

if($num > 0){
    $users = [];

    while($user = $rdej->fetch(PDO::FETCH_ASSOC)){

        $users[] = array(
                        "ID" => $user['ID'],
                        "username" => $user['username'],
                        "city" => $user['city'],
                        "age" => $user['age']
                    );
    }

    // 200 OK - request reusit
    http_response_code(200);

    echo json_encode($users);
  

特别不要在全局范围内尝试not to use extract()