1
\$\begingroup\$

I have a multi dimensional array like this:

[0] => 
    ['batch_id'] => '1'
    ['some_stuff'] => 'values'
    [0] =>
        ['unit_id'] => '12'
        ['some_stuff'] => 'values'
    [1] =>
        ['unit_id'] => '41'
        ['some_stuff'] => 'values'

This comes from an external API, so I have no control over the original formatting of the array.

What would be the preferred (least overhead) way to take all the 'unit_id' and 'batch_id' fields, remove them from the group of values about the item, and assign that value to the item's key?

What I've tried (and works, but I want to find something cleaner):

public function fixArray($batches) {
    $batchfix = array();
    foreach($batches as $batch) {
        $unitfix = $array;
        $batch_temp = $batch;
        array_shift(array_shift($batch_temp)); // Get rid of id details
        foreach($batch_temp as $unit)
            $unittemp = $unit;
            array_shift($unittemp);
            $unitfix[$unit['unit_id']] = $unittemp;
        $batchfix[$batch['batch_id']] = $batch;
    }
    return $batchfix;
}

Any suggestions?

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

I suppose the result you want to have is this:

    Array
    (
        [1] => Array
            (
                [stuff] => values
                [units] => Array
                    (
                        [12] => Array
                            (
                                [stuff] => values
                            )
                        [41] => Array
                            (
                                [stuff] => values
                            )
                    )
            )
    )

In this case you can use the code:

    public function fixArray($originalBatches) {
        $batches = array();
        foreach($originalBatches as $batch) {
            $units = array();
            $batch_id = $batch['batch_id'];
            unset($batch['batch_id']);
            foreach ($batch as $key => $value) {
                if (is_numeric($key) && !empty($value['unit_id'])) {
                    $units[$value['unit_id']] = array_slice($value, 1);
                    unset($batch[$key]);
                }
            }
            $batches[$batch_id] = array_merge($batch, array('units' => $units));
        }
        return $batches;
    }

Still the use of the 2 foreach is not a very good practice. You can change the code accordingly to use array_walk. This would be much faster.

\$\endgroup\$
0

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.