如何在创建多维数组时设置顶级变量


How to set the top level variable when creating a multidimensional array?

我有一个foreach循环,将数据插入多维数组。

    foreach ($charts_list as $chart_list) {
      $category = $chart_list->category;
      if (isset($chart_options[$category])) {
         $chart_options[$category][] = $chart_list;
      } else {
         $chart_options[$category] = array($chart_list);
      }
    }

我得到一个这样的数组:

array:2 [▼
  "twitter" => array:3 [▼
    0 => {#271 ▼
      +"id": 1
      +"option_id": "DJ8RhoB"
      +"title": "Followers Growth"
      +"description": "See your followers growth"
      +"category": "twitter"
      +"created_at": "2016-05-09 10:44:54"
      +"updated_at": "2016-05-09 10:44:54"
    }
    1 => {#272 ▼
      +"id": 2
      +"option_id": "tqP3Bri"
      +"title": "Friends growth"
      +"description": "See your friends growth"
      +"category": "twitter"
      +"created_at": "2016-05-09 10:45:24"
      +"updated_at": "2016-05-09 10:45:24"
    }
    2 => {#273 ▼
      +"id": 3
      +"option_id": "v74DudJ"
      +"title": "Statuses count"
      +"description": "See your content growth"
      +"category": "twitter"
      +"created_at": "2016-05-09 10:45:46"
      +"updated_at": "2016-05-09 10:45:46"
    }
  ]
  "facebook" => array:1 [▼
    0 => {#274 ▼
      +"id": 4
      +"option_id": "fXj8wU5"
      +"title": "Friends growth"
      +"description": "See your friends growth"
      +"category": "facebook"
      +"created_at": "2016-05-09 13:08:21"
      +"updated_at": "2016-05-09 13:08:21"
    }
  ]
]

在顶级数组上,我需要将其设置为'category' => $category,它应该打印"category": twitter。我已尝试将$chart_options[$category]设置为$chart_options['category' => $category. But I get a parse error分析错误:语法错误,意外的"=>"(T_DOUBLE_ARROW),应为"]''"。如何将顶级数组设置为类别?

看起来您实际上只是在尝试访问数组中的键和值。

PHP foreach允许您通过指定一个附加参数来访问数组的键,而不是典型的:

foreach ($array as $value)

你可以做:

foreach ($array as $key => $value)

我希望这能有所帮助。

这不是很清楚,但我想你想要这个:

$chart_options['category'] = $category;

您可能需要尝试

$chart_options['category'][$category][] = $category;

在else部分添加元素category

您的代码

$chart_options[$category] = array($chart_list);

更换后,它将看起来像低于

$chart_options['category'][$category] = array($chart_list);
                  ^

完整代码

foreach ($charts_list as $chart_list) {
  $category = $chart_list->category;
  if (isset($chart_options[$category])) {
     $chart_options[$category][] = $chart_list;
  } else {
     $chart_options['category'][$category] = array($chart_list);
  }
}