简体   繁体   English

根据值从数组创建一个数组,并将匹配项包含在数组中

[英]Create an array from an array based on value and include matches within as an array

I'm wanting to group my data by a specific value (parent name) and then merge all the items that share the same parent name under a "items" array我想按特定值(父名称)对我的数据进行分组,然后将所有共享相同父名称的项目合并到“项目”数组下

However it's overwriting the items array, not adding to it, so for example "items" in the output should have multiple items not just one.但是它会覆盖 items 数组,而不是添加到它,因此例如 output 中的“items”应该有多个项目,而不仅仅是一个。

Any ideas?有任何想法吗?

$result = array();
foreach ($page->products_codes as $option) {
    $result[$option->parent->name]["title"] = $option->parent->title;
    $result[$option->parent->name]["items"] = $option->title;
}

Outputs as:输出为:

array (
  'fixture' => 
  array (
    'title' => 'Fixture',
    'items' => 'Pinhole90 Fixed with LED51',
  ),
  'finish' => 
  array (
    'title' => 'Finish',
    'items' => 'RAL',
  ),
  'ip-rating' => 
  array (
    'title' => 'IP Rating',
    'items' => 'IP54',
  ),
  'emergency' => 
  array (
    'title' => 'Emergency',
    'items' => 'Maintained 3hr Self Test',
  ),
  'installation' => 
  array (
    'title' => 'Installation',
    'items' => 'Plaster-kit for seamless flush appearance',
  ),
  'led' => 
  array (
    'title' => 'LED',
    'items' => 'LED50 ONE',
  ),
  'cct' => 
  array (
    'title' => 'CCT',
    'items' => '90 CRI 4000K',
  ),
  'beam-angle' => 
  array (
    'title' => 'Beam Angle',
    'items' => '38°',
  ),
  'protocol' => 
  array (
    'title' => 'Protocol',
    'items' => 'Bluetooth',
  ),
  'louvre-lens' => 
  array (
    'title' => 'Louvre/Lens',
    'items' => 'Heavy Spread Lens',
  ),
)

Any thoughts?有什么想法吗?

Based on the preferred data structure you specified:根据您指定的首选数据结构:

$result = array();
foreach ($page->products_codes as $option) {
    $result[$option->parent->name]["title"] = $option->parent->title;
    $result[$option->parent->name]["items"][] = $option;
}

$result = array_values($result);

Here's a working example: https://3v4l.org/u9XBk这是一个工作示例: https://3v4l.org/u9XBk

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

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