I have a PHP array which contains objects like this
Array
(
[0] => stdClass Object
(
[label] => Test 1
[session] => 2
)
[1] => stdClass Object
(
[label] => Test 2
[session] => 2
)
[2] => stdClass Object
(
[label] => Test 3
[session] => 42
)
[3] => stdClass Object
(
[label] => Test 4
[session] => 9
)
)
I am trying to count the number of unique sessions within this array. I can do it when the whole thing is an array, but I am struggling to work it out when the array contains objects.
Do I need to convert the objects into arrays or is there a way of doing it with the data in its current format?
https://www.php.net/manual/en/function.array-column.php :
Version Description 7.0.0 Added the ability for the input parameter to be an array of objects.
Use array_column to generate new keys using the session column values. This effectively removes duplicate keys.
Code: ( Demo )
$array = [
(object)['label' => 'Test 1', 'session' => 2],
(object)['label' => 'Test 2', 'session' => 2],
(object)['label' => 'Test 3', 'session' => 42],
(object)['label' => 'Test 4', 'session' => 9],
];
echo sizeof(array_column($array, null, 'session'));
Output:
3
Or in a loop:
foreach ($array as $obj) {
$result[$obj->session] = null;
}
echo sizeof($result);
Both techniques avoid the extra function call of array_unique
and leverage the fact that arrays cannot store duplicate keys.
I have tried your code and here created sample data
$comments= array();
$comment = new stdClass;
$comment->label = 'Test 1';
$comment->session = '2';
array_push($comments, $comment);
$comment = new stdClass;
$comment->label = 'Test 2';
$comment->session = '2';
array_push($comments, $comment);
$comment = new stdClass;
$comment->label = 'Test 3';
$comment->session = '42';
array_push($comments, $comment);
$comment = new stdClass;
$comment->label = 'Test 4';
$comment->session = '9';
array_push($comments, $comment);
Here is code I tried to get the unique value. this way you can get any field unique value
$uniques = array();
foreach ($comments as $obj) {
$uniques[$obj->session] = $obj;
}
echo "<pre>";
print_r($uniques);
echo "</pre>";
You could also use array_map to only keep the value of session
in the array, then use array_unique to remove the duplicate entries and finally count the unique items.
If for example your array variable is called $array
:
$result = array_map(function($x){
return $x->session;
}, $array);
echo count(array_unique($result));
That will result in:
3
The object within an array can be accessed with $array[0]
where the 0
stands for the object. To access the objects property you can do $object->session
.
To go throught every objects session property you can do:
foreach ($array as $object) {
echo $object->session . "<br/>";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.