1

I am trying to use my API to display data from a database but I get this error:

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

How can I make it so I only get the array starting with 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;
            });
        }
}]);

How can I make it so I only get the array starting with ID:1?

Also, 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 Answers2

0

When you have "useri" as index, json_encode output always a json object.

To output a json array, the array to encode should just be indexed array.

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

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

So you could just do somehow like this

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);
}

If you need a reference to useri then you can do it in javasript in the client side

hery
  • 49
  • 6
0

It is your code that is creating the extra information, so just stop adding the sub arrays you dont want to have

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);

Try not to use extract() specially not in the global scope

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149