简体   繁体   English

PHP-Foreach变量仅在读取时有效

[英]PHP - Foreach variable works only if read

I am trying to read posts under each category as shown below. 我正在尝试阅读每个类别下的帖子,如下所示。 There are multiple categories with id "4", "3", "2", "1". 有多个类别,其ID为“ 4”,“ 3”,“ 2”,“ 1”。 Only for category "1" there is a post available. 仅对于类别“ 1”有可用的帖子。

foreach ($wp_categories as $wp_category) {

  $id = $wp_category->term_taxonomy_id;
  //if($id == "1") {
   $posts = $json_api->introspector->get_posts(array(
                  'cat' => $id
                  ));
  //}
  $result[] = $posts;         
}

return $result;

In the above code if I just uncomment the if condition, I am getting the posts in the result array. 在上面的代码中,如果我只是取消注释if条件,那么我将在结果数组中获取帖子。 But if this is commented I am not getting the posts in result. 但是,如果对此发表评论,我不会得到结果。

I am new to PHP and above condition is not making any sense. 我是PHP新手,以上条件没有任何意义。 It would be of great help if someone could explain why having the if condition is making the post available in the result. 如果有人可以解释为什么使用if条件可以在结果中提供该帖子,那将有很大的帮助。

dumping $wp_categories below 在下面转储$ wp_categories

{
  "status": "ok",
  "0": {
    "term_id": "5",
    "name": "Category 5",
    "slug": "category5",
    "term_group": "0",
    "term_order": "1",
    "term_taxonomy_id": "5",
    "taxonomy": "category",
    "description": "",
    "parent": "0",
    "count": "0"
  },
  "1": {
    "term_id": "2",
    "name": "Category 4",
    "slug": "category4",
    "term_group": "0",
    "term_order": "2",
    "term_taxonomy_id": "2",
    "taxonomy": "category",
    "description": "",
    "parent": "0",
    "count": "0"
  },
  "2": {
    "term_id": "3",
    "name": "Category 3",
    "slug": "category3",
    "term_group": "0",
    "term_order": "3",
    "term_taxonomy_id": "3",
    "taxonomy": "category",
    "description": "",
    "parent": "0",
    "count": "0"
  },
  "3": {
    "term_id": "4",
    "name": "abc",
    "slug": "abc",
    "term_group": "0",
    "term_order": "4",
    "term_taxonomy_id": "4",
    "taxonomy": "category",
    "description": "",
    "parent": "0",
    "count": "0"
  },
  "4": {
    "term_id": "1",
    "name": "Others",
    "slug": "others",
    "term_group": "0",
    "term_order": "5",
    "term_taxonomy_id": "1",
    "taxonomy": "category",
    "description": "",
    "parent": "0",
    "count": "1"
  }
}

This is simply shows that it will be true only in case of id 1: 这只是表明只有在id 1的情况下它才是正确的:

if($id == "1") {

I think this should be: 我认为应该是:

if(isset($id) && $id != '') {

to get the all the post. 获得所有职位。

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

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