John Davidson

php - Loop through array contain objects and create different arrays from it

0 comments
Message:


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
)
)


My Answer:
stdClass Object
(
[user_name] => "John"
[length] => 60
)
[1] = stdClass Object
(
[user_name] => "Jane"
[length] => 120
)
[2] = stdClass Object
(
[user_name] => "John"
[length] => 90
)
[3] = stdClass Object
(
[user_name] => "Jane"
[length] => 180
)
)

php
// Initialize an empty array to store the results
$results = [];

// Loop through the array of objects
foreach ($array as $obj) {
// Check if the user name already exists in the results array
if (array_key_exists($obj->user_name, $results)) {
// If it exists, add the length to the existing sum
$results[$obj->user_name]['length'] += $obj->length;
} else {
// If it doesn't exist, create a new entry with the user name and length
$results[$obj->user_name] = [
'user_name' => $obj->user_name,
'length' => $obj->length
];
}
}

// Convert the associative array to a simple array
$results = array_values($results);

// Print the results
print_r($results);


This code will loop through the array of objects, create a new array for each unique user name, and calculate the sum of their lengths. The final output will be an array of arrays, each containing the user name and the sum of their lengths.

Rate this post

4 of 5 based on 4712 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us