在php

时间:2015-10-14 11:00:04

标签: php arrays

我试图在php中创建和数组对象以发送到我的AngularJS应用程序格式想要的是

[
 {},
 {},
 {}
]

但是当我运行我的代码时,我得到一个外部数组和一个内部数组,并且这些对象位于内部数组中。我不希望2个数组只是一个外部数组

继续得到什么

[
[
    {
        "id": "16",
        "post_title": "Gotta love Batman",
        "author_name": "Clinton Dsouza",
        "publish_date": "Tuesday, October 13th 2015, 4:50:50 pm"
    },
    {
        "id": "15",
        "post_title": "Web 2.0 ipsum...Again",
        "author_name": "Clinton Dsouza",
        "publish_date": "Tuesday, October 13th 2015, 4:48:42 pm"
    },
    {
        "id": "10",
        "post_title": "Vegetable Ipsum",
        "author_name": "Clinton Dsouza",
        "publish_date": "Tuesday, October 13th 2015, 1:36:57 pm"
    },
    {
        "id": "9",
        "post_title": "Yet another Harry Potter ipsum",
        "author_name": "Clinton Dsouza",
        "publish_date": "Tuesday, October 13th 2015, 1:28:55 pm"
    }
]
]

因为你可以看到数组里面有一个数组。我怎么去修复它以获得我想要的格式

我的代码

try {
    $resultArray = null;
    $sql = "SELECT id,post_title,author_name,publish_date FROM posts ORDER BY id DESC LIMIT 4 OFFSET $data->offset ";
    $result = mysql_query($sql) or trigger_error(mysql_error() . $sql);
    $count = mysql_num_rows($result);
    $index = 0;
    if ($count > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $resultArray[$index]=new StdClass();
            $resultArray[$index]->id = $row['id'];
            $resultArray[$index]->post_title = $row['post_title'];
            $resultArray[$index]->author_name = $row['author_name'];
            $resultArray[$index]->publish_date = $row['publish_date'];

            $index++;

        }
        $response['status'] = 'Success';
        $response['message'] = 'Data present';
        $response['results'] = $resultArray;
    } else {
        $response['status'] = 'Error';
        $response['message'] = 'No Posts found';
    }
    echo json_encode($response);

} catch (Exception $e) {
    $response['status'] = 'Error';
    $response['message'] = $e->getMessage();
    echo json_encode($response);
    die();
}

2 个答案:

答案 0 :(得分:1)

当你使用json_encode时,它会自动将数组转换为对象,即javascript对象表示法。不需要操作。只有你必须这样做 -

if ($count > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $resultArray[]=$row;
        }

答案 1 :(得分:0)

解决此问题的一种方法是:您可以在数组中编入索引(以获取数组中的数组)并将其值存储在新变量中。这样你就可以摆脱“双阵”。