Home > Enterprise >  Loop through array contain objects and create different arrays from it
Loop through array contain objects and create different arrays from it

Time:01-08

I have this array of objects and I need to produce arrays from it to be that every array contains the [user name] and the sum of his [length] the length is time in seconds.

What's the best way for it?

Array
(
    [0] => stdClass Object
        (
            [length] => 4658
            [user_id] => 1922053
            [user_name] => Walled
        )

    [1] => stdClass Object
        (
            [length] => 5
            [user_id] => 1922053
            [user_name] => Walled
        )
    [2] => stdClass Object
        (
            [length] => 5555
            [user_id] => 19220
            [user_name] => Michael
        )

    [3] => stdClass Object
        (
            [length] => 2552
            [user_id] => 19220
            [user_name] => Michael
        )
)

CodePudding user response:

This will process the old array into a new one, It uses the user_id as the key of the new array so it can check if it is creating a new occurance or just adding the length to an existing occurance in the new array

$array = [
    (object)['length' => 4658, 'user_id' => 1922053, 'user_name' => 'Walled'],
    (object)['length' => 5, 'user_id' => 1922053, 'user_name' => 'Walled'],
    (object)['length' => 5555, 'user_id' => 19220, 'user_name' => 'Michael'],
    (object)['length' => 2552, 'user_id' => 19220, 'user_name' => 'Michael']
];

$new = [];
foreach( $array as $a ) {
    if ( ! array_key_exists($a->user_id, $new) ) {
        $new[$a->user_id] = $a;    
    } else {
        echo $new[$a->user_id]->length . PHP_EOL;
        $new[$a->user_id]->length  = $a->length;    
    }
    
}

print_r($new);

RESULT

Array
(
    [1922053] => stdClass Object
        (
            [length] => 4663
            [user_id] => 1922053
            [user_name] => Walled
        )
    [19220] => stdClass Object
        (
            [length] => 8107
            [user_id] => 19220
            [user_name] => Michael
        )
)
  •  Tags:  
  • Related