0

I want to group a PHP array with a data structure like this:

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

I tried this:

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

and I expected it to display as:

"data": [ {"seq": [{"Aug":1},{"Jul":1},{"Aug":2},{"Jul":2}]}]
1
  • Are you able to achieve it by foreach loop, if yes please share that code ? and it is not array only it is array of objects. Commented Jul 12, 2019 at 5:47

2 Answers 2

1

As commented by the other user, array_column will not work here.

The docs describe what the method does, and that's not what you want:

array_column() returns the values from a single column of the input, identified by the column_key

This should work though (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']));
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can not use array_column here because you have non-unique values. You need to loop through array. Please see below code

$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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.