简体   繁体   中英

php iterate through array of objects inside an array

I am trying to loop through all posts in my database and grab their id. Here is what I have so far:

$posts = $db->select("posts","*",array());

foreach ($posts as $value) {
    $response['postvalue'] = $value;
}

When I run the code above I get this in my console.

在此处输入图片说明

inside those objects I have a property 'id'.

When I run this:

$posts = $db->select("posts","*",array());

foreach ($posts as $value) {
    $response['postvalue'] = $value->id;
}

I get a null value:

在此处输入图片说明

What am I doing wrong?

UPDATE:

在此处输入图片说明

Update your code to add a var dump and post the data structure of the posts array. Currently it would be anyones best / lucky guess without knowing how that data looks.. this way people will be able to help you

$posts = $db->select("posts","*",array());
//var_dump($posts); 
foreach ($posts->data as $value) {
    $response['postvalue'][] = $value['id'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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