Skip to content
Advertisement

formatting an array of array that contain similar key value

i have an array of arrays like this one

array(4) {
  [0] => array(2) {
    ["option"] => string(5) "64310"
    ["choice"] => string(6) "221577"
  }
  [1] => array(2) {
    ["option"] => string(5) "64310"
    ["choice"] => string(6) "221578"
  }
  [2] => array(2) {
    ["option"] => string(5) "64305"
    ["choice"] => string(6) "221538"
  }

}

i want to obtain a result like this one

array(2) {
  [0] => array(2) {
    ["option"] => string(5) "64310"
    ["choices"] => array(2){
       ["choice"] => string(6) "221577"
       ["choice"] => string(6) "221578"
    }
  }
}

how can i proceed, thank you in advance

Advertisement

Answer

Something like this will help you achieve the desired result;

<?php

    $data = [
        [
            'option' => '64310',
            'choice' => '221577'
        ],
        [
            'option' => '64310',
            'choice' => '221578'
        ],
        [
            'option' => '64305',
            'choice' => '221538'
        ]
    ];

    $res = [];
    foreach($data as $d) {

        // Check if we've already got this option
        // Note the '&' --> Check link below
        foreach($res as &$r) {
            if (isset($r['option']) && $r['option'] === $d['option']) {

                // Add to 'choices'
                $r['choices'][] = $d['choice'];

                // Skip the rest of both foreach statements
                continue 2;
            }
        }

        // Not found, create
        $res[] = [
            'option' => $d['option'],
            'choices' => [ $d['choice'] ],
        ];
    };

    print_r($res);

& –> PHP “&” operator

Array
(
    [0] => Array
        (
            [option] => 64310
            [choices] => Array
                (
                    [0] => 221577
                    [1] => 221578
                )
        )
    [1] => Array
        (
            [option] => 64305
            [choices] => Array
                (
                    [0] => 221538
                )
        )
)

Try online!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement