0

I have data from a database that I want to convert to another format. The data is in the form of an array as below

$array = [
    ['type 1', 'Country 1', 243],
    ['type 1', 'Country 2', 500],
    ['type 1', 'Country 3', 400],
    ['type 2', 'Country 1', 234],
    ['type 2', 'Country 2', 1234],
    ['type 2', 'Country 3', 1400],
    ['type 3', 'Country 1', 222],
    ['type 3', 'Country 2', 25],
    ['type 3', 'Country 3', 120],
];

How to convert array above with php to array like this below:

$toArray = [
    [
        'name' => 'type 1',
        'data' => [
            [
                'name' => 'Country 1',
                'y' => 243
            ],
            [
                'name' => 'Country 2',
                'y' => 500
            ],
            [
                'name' => 'Country 3',
                'y' => 400
            ],
        ]
    ],
    [
        'name' => 'type 2',
        'data' => [
            [
                'name' => 'Country 1',
                'y' => 234
            ],
            [
                'name' => 'Country 2',
                'y' => 1234
            ],
            [
                'name' => 'Country 3',
                'y' => 1400
            ],
        ]
    ],
    ...
];

Code so far

$toArray = []; 
foreach($models as $key => $model) { 
    $type = [ 'name' => $model->type, 'data' => [] ]; 
    if(in_array($type, $toArray)) { 
        continue; 
    } 
    $toArray[] = $type; 
}

I'm confuse about this, can someone guide me?

0

2 Answers 2

2

An easier way would be to use the model name as the key to the array and check if it isn't already set. If not it will add the name and a blank data element (similar to what you are already doing). Then it will add the other information to this data element.

$toArray = [];
foreach($array as $key => $model) {
    if ( !isset($toArray[$model->type]) )  {
        $toArray[$model->type] = [ 'name' => $model->type, 'data' => [] ];
    }
    $toArray[$model->type]['data'][] = [ 'name' => $model->country, 
                'y' => $model->value ];
}

// Remove keys if not needed
$toArray = array_values($toArray);
Sign up to request clarification or add additional context in comments.

1 Comment

You're right Nigel, my data($array) is an object from active record, so name will be $model->type, country will be $model->country, and y will be $model->value
1

You can iterate using foreach

foreach($array as $v){
  if(isset($final[$v[0]])){
    $final[$v[0]]['data'][] = ['name' => $v[1], 'y' => $v[2]];
  }else{
    $final[$v[0]] = ['name' => $v[0],'data' =>[
            ['name' => $v[1], 'y' => $v[2]]
        ]
    ];
  }
}

Working example :- https://3v4l.org/lu7bk

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.