基于键的单独数组对象-PHP

时间:2018-07-17 14:30:42

标签: php arrays

我有一个包含数据子集的数组,如下所示:

"options":[  
{  
    "id":"13",
    "option_name":"M",
    "option_id":"1",
    "label":"Size"
},
{  
    "id":"13",
    "option_name":"L",
    "option_id":"1",
    "label":"Size"
},
{  
    "id":"13",
    "option_name":"BLUE",
    "option_id":"1",
    "label":"Color"
},
{  
    "id":"13",
    "option_name":"GREEN",
    "option_id":"1",
    "label":"Color"
}
]

我想循环进入此数组,并根据键标签分离对象/子集。如下:

"options":[
{
    "label":"Size",
    "optionsArray":[
            {
                "id":"11",
                "option_name":"XL",
                "option_id":"1",
                "label":"Size",
            },
            {
                "id":"12",
                "option_name":"L",
                "option_id":"1",
                "label":"Size",
            }
        ]
},
{
    "label":"Color",

        "optionsArray":[
            {
                "id":"11",
                "option_name":"BLUE",
                "option_id":"1",
                "label":"Color",
            },
            {
                "id":"12",
                "option_name":"GREEN",
                "option_id":"1",
                "label":"Color",
            }
        ]
}
]

如何用PHP实现呢?

由于此帖子已经充满了代码,所以stackoverflow不允许我粘贴当前的代码尝试,所以我将尝试将简单的结构粘贴为纯文本。

$keys = array_keys(current($options));

$len = count($options);
foreach($keys as $key){

// Access the key first 

    for($i=0;$i<$len; $i++){

    // access the row later

        echo $array[$i][$key];
    }
}

2 个答案:

答案 0 :(得分:2)

我会那样做:

$result = [];
foreach ($options as $option) {
    if (!isset($result[$option['label']])) {
        $result[$option['label']] = [
            'label' => $option['label'],
            'optionsArray' => []
        ];
    }
    $result[$option['label']]['optionsArray'][] = $option;
}
$result = array_values($result);

答案 1 :(得分:1)

<?php
// Decode the JSON (true for using associative arrays)
$array = json_decode($json, true);

// Initialize three arrays    
$colors = [];
$sizes = [];
$unknown = [];

// Loop and seperate them using a switch
foreach ($array['options'] as $o) {
    if (! isset($o['label'])) {
        trigger_error('label not in object', E_USER_WARNING);
    }

    switch($o['label']) {
        case 'Size':
            $sizes[] = $o;
            break;

        case 'Color':
            $colors[] = $o;
            break;

        // Put all malformed objects into this array
        default:
            $unknown[] = $o;
    }
}

// You can now easily build your new array
$output = ['options' => [
    ['label' => 'Size', 'optionsArray' => $sizes],
    ['label' => 'Color', 'optionsArray' => $colors]
]];