我想使用键值对PHP数组进行分组

时间:2019-07-12 05:41:30

标签: php arrays json

我想用这样的数据结构对PHP数组进行分组:

"data": [
        {
            "seq": "1",
            "created_month": "Aug"
        },
        {
            "seq": "1",
            "created_month": "Jul"
        },
        {
            "seq": "2",
            "created_month": "Aug"
        },
        {
            "seq": "2",
            "created_month": "Jul"
        }
    ]

我尝试过:

$data   = array_column($data,'seq','created_month');

,我希望它显示为:

"data": [ {"seq": [{"Aug":1},{"Jul":1},{"Aug":2},{"Jul":2}]}]

2 个答案:

答案 0 :(得分:1)

根据其他用户的评论,array_column在这里不起作用。

docs描述了该方法的作用,而这不是您想要的:

  

array_column()从输入的单个列返回值,   由column_key标识

这应该可以(ideone):

$data = '[
    {
        "seq": "1",
        "created_month": "Aug"
    },
    {
        "seq": "1",
        "created_month": "Jul"
    },
    {
        "seq": "2",
        "created_month": "Aug"
    },
    {
        "seq": "2",
        "created_month": "Jul"
    }
]';

$data = json_decode($data, true);
$transformedData = array();
$transformedData["data"] = array();
array_push($transformedData["data"], array("seq" => array_map('convertItem', $data)));

print_r(json_encode($transformedData));

function convertItem($item) {
  return array($item['created_month'] => intval($item['seq']));
}

答案 1 :(得分:0)

您不能在此处使用array_column,因为您具有非唯一值。您需要遍历数组。请参见下面的代码

$data = json_decode( $data, true);

$formatArray = array();
foreach( $data as $d ) {
    $formatArray[] = array( $d['created_month'] => $d['seq'] );
}

$j = array();
$j['seq'] = $formatArray;
echo json_encode( $j );