繁体   English   中英

在php中创建对象数组

[英]create array of objects in php

我正在尝试在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();
}

当您使用json_encode时,它会自动将数组转换为对象,即javascript对象表示法..无需进行操作。只需要按照-

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

修复它的一种方法是:您可以在数组中建立索引(以在数组中获取数组)并将其值存储在新变量中。 这样,您将摆脱“双重数组”。

暂无
暂无

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

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