Search code examples
phparraysmultidimensional-arrayconditional-statementsgrouping

Group array rows by one column and only create a subarray from another column if more than one value


How can I group row data from a two-dimensional array and only create a subarray of another column if the respective group contains more than one value?

In other words, I need to group rows by id and conditionally restructure an array of arrays to have a variable depth of either 2 or 3 levels.

Input:

[
    ['id' => 567, 'value' => 780],
    ['id' => 676, 'value' => 743],
    ['id' => 676, 'value' => 721],
    ['id' => 234, 'value' => 766],
    ['id' => 234, 'value' => 680]
]

Desired output:

[
    ['id' => 567, 'value' => 780],
    ['id' => 676, 'value' => [743, 721]],
    ['id' => 234, 'value' => [766, 680]]
]

Solution

  • Are you sure you want to have the value as an integer when there is one value and an array when there are more?

    <?php
    $array = array(
        array('id' => 567, 'value' => 780),
        array('id' => 676, 'value' => 743),
        array('id' => 676, 'value' => 721),
        array('id' => 234, 'value' => 766),
        array('id' => 234, 'value' => 680)
    );
    
    foreach ($array as $item) {
        $result[$item['id']][] = $item['value'];
    }
    
    foreach ($result as $id => $value) {
        if (count($value) > 1) {
            $output[] = array(
                'id' => $id,
                'value' => $value
            );
        } else {
            $output[] = array(
                'id' => $id,
                'value' => $value[0]
            );
        }
    }
    
    echo '<pre>';
    print_r($output);
    echo '</pre>';
    ?>
    

    If not

    <?php
    $array = array(
        array('id' => 567, 'value' => 780),
        array('id' => 676, 'value' => 743),
        array('id' => 676, 'value' => 721),
        array('id' => 234, 'value' => 766),
        array('id' => 234, 'value' => 680)
    );
    
    foreach ($array as $item) {
        $result[$item['id']][] = $item['value'];
    }
    
    foreach ($result as $id => $value) {
        $output[] = array(
            'id' => $id,
            'value' => $value
        );
    }
    
    echo '<pre>';
    print_r($output);
    echo '</pre>';
    ?>