![](/img/trans.png)
[英]How to get a specific (POST) value from foreach loop instead of getting the last index in PHP?
[英]issue to get post index in foreach
我有問題從php中的以下代碼獲取帖子索引
stdClass Object (
[blog] => stdClass Object (
[ask] => 1
[ask_anon] => 1
[ask_page_title] => Ask me anything
[can_subscribe] =>
[description] =>
[is_adult] =>
[is_nsfw] =>
[name] => fashion
[posts] => 3068
[reply_conditions] => 3
[share_likes] =>
[subscribed] =>
[title] => Fashion
[total_posts] => 3068
[updated] => 1511888740
[url] => http://fashion.tumblr.com/
[is_optout_ads] => 1
)
[posts] => Array (
[0] => stdClass Object (
[type] => photo
[blog_name] => fashion
[id] => 167980084706
[post_url] => http://fashion.tumblr.com/post/167980084706/art-by-lucamaininipsychodiva
[slug] => art-by-lucamaininipsychodiva
[date] => 2017-11-28 17:05:40 GMT
[timestamp] => 1511888740
[state] => published
[format] => html
[reblog_key] => TQXtN3TU
[tags] => Array (
[0] => luca mainini
[1] => gif
[2] => art
[3] => fashion
[4] => design
[5] => fashionontumblr
)
[short_url] => https://tmblr.co/ZSVahx2SSPAtY
[summary] => Art by @lucamaininipsychodiva
[is_blocks_post_format] =>
[recommended_source] =>
[recommended_color] =>
[note_count] => 75
[source_url] => http://lucamaininipsychodiva.tumblr.com/post/120540766379/gif-collage-for-vulkan-magazine
[source_title] => lucamaininipsychodiva
您可以申請:-
$object->posts[0]->blog_name;
或者,如果您想使用foreach():-
foreach($object->posts as $key=>$value){
echo $key;
echo $value->id;
}
注意:-在第二個中, $key
是子數組的索引,例如0、1、2、3 ..,而$value
是子數組本身。
首先,首先要確定的是,當您從json解碼為數組時,您需要使用,true
因此在此stdclass對象之前的步驟中使用$array=json_decode($myArray,true);
這將為您提供所需的數組。 在多維數組易於處理之后,您只需要在其周圍循環:
foreach ($array['posts'] as $row){
echo $row['id'] //for example
}
如果仍然要使用stdclass對象,則仍然可以像這樣訪問它:
foreach ($result->posts as $row) {
echo $row->id;
}
我總是更喜歡以數組來處理,但這取決於您。 這些是我最適合的2個解決方案選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.