I have a PHP object like below and all I want to know whats the the easiest way to get a count of objects where the property 'typeId' = 3
Array
(
[0] => ABC Object
(
[id] => 13
[typeId] => 3
[sortOrder] => 0
)
[1] => ABC Object
(
[id] => 12
[typeId] => 2
[sortOrder] => 0
)
[2] => ABC Object
(
[id] => 14
[typeId] => 4
[sortOrder] => 0
)
[3] => ABC Object
(
[id] => 15
[typeId] => 3
[sortOrder] => 0
)
)
A simple foreach counter should do:
$count = 0;
foreach ($array as $object) {
if ($object->typeId == 3) $count++;
}
No need to over complicate things
From my point of view, a much nicer solution is to use the array_filter function:
$newarray = array_filter( $old_array, function($object) { return $object->typeId == 3; } );
(note: inline functions only work since PHP 5.3)
Just create a temporary variable called objectCount or something similar, loop through your array and when you find an object where the typeId equals 3 add 1 to objectCount.
Related
I have array that contain an score and id that calculated from other function
And I have user info that retried from DB.
In Both array ID's are the same
how can I push them to One array?
Score Array
Array
(
[0] => Array
(
[id] => 85
[total_cnt] => 2006
)
[1] => Array
(
[id] => 86
[total_cnt] => 1014
)
[2] => Array
(
[id] => 92
[total_cnt] => 6
)
[3] => Array
(
[id] => 93
[total_cnt] => 6
)
)
user info
Array
(
[0] => Array
(
[id] => 52
[user_phone] => 00000000
[user_email] => test#yahoo.com
[user_name] => yahoo
[user_picture] =>FG6K7Z3XTc.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 1
[user_reg_date] => 2017-05-16 13:52:35
)
[1] => Array
(
[id] => 78
[user_phone] => 000000001
[user_email] => google#gmail.com
[user_name] => google
[user_picture] =>XqWKSDVci.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 0
[user_reg_date] => 2017-05-16 13:52:35
)
)
My Desire output
Array
(
[0] => Array
(
[id] => 86 <--Same ID in both arrays
[user_phone] => 00000000
[user_email] => test#yahoo.com
[user_name] => yahoo
[user_picture] =>FG6K7Z3XTc.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 1
[user_reg_date] => 2017-05-16 13:52:35
[total_cnt] => 1014 <-- first array field added
)
I want an optimized code and I won't use loop for to do this
Thanks for your help
Use PHP's built-in function array_merge. Use the official PHP documentation for additional guidance # http://php.net/manual/en/function.array-merge.php
Update:
A much better approach seems to be "array_column":
$cnts = array_column($scores, 'total_cnt', 'id');
foreach ($userInfo as $key => $item) {
$userInfo[$key]['total_cnt'] = $cnts[$item['id']];
}
I made some "naive" benchmark tests using microtime() and test data like your arrays:
Execution times:
10000 items in both arrays:
array_column 0.005s vs 0.85s foreach
20000 items in both arrays:
array_column 0.011s vs 18s foreach
Original answer:
You can also use foreach loops like this:
foreach ($userInfo as $userKey => $item) {
foreach ($scores as $scoreKey => $score) {
if ($score['id'] == $item['id']) {
$userInfo[$userKey]['total_cnt'] = $score['total_cnt'];
unset($scores[$scoreKey]);
break;
}
}
}
The unset within the second loop "removes" the processed score from the $scores array to reduce the number of iteration cycles in the next run. Please note that the $scores array will be empty afterwards, maybe create a copy of it and work with that.
I have these two arrays:
1:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Type 1
[rate] => 100.00
)
[1] => stdClass Object
(
[id] => 2
[name] => Type 2
[rate] => 75.00
)
[2] => stdClass Object
(
[id] => 3
[name] => Type 3
[rate] => 50.00
)
[3] => stdClass Object
(
[id] => 4
[name] => Type 4
[rate] => 50.00
)
)
2:
Array
(
[0] => stdClass Object
(
[name] => Type 1
[rate] => 125
)
[1] => stdClass Object
(
[name] => Type 2
[rate] => 85
)
[2] => stdClass Object
(
[name] => Type 3
[rate] => 65
)
)
What I need to do is compare the two arrays, and append missing items from 1st array to the 2nd one. This will always be the case first array will have more items than the second one.
I have tried using something like:
$result = array_udiff($array1,$array2,
function ($obj_a, $obj_b) {
return $obj_a->name - $obj_b->name;
}
);
but it just returns an empty array
This?
<?php
$arr1 = array(
(object)array("id"=>1,"name"=>"type 1","rate"=>100.00),
(object)array("id"=>2,"name"=>"type 2","rate"=>75.00),
(object)array("id"=>3,"name"=>"type 3","rate"=>50.00),
(object)array("id"=>4,"name"=>"type 4","rate"=>50.00)
);
$arr2 = array(
(object)array("name"=>"type 1","rate"=>125),
(object)array("name"=>"type 2","rate"=>85),
(object)array("name"=>"type 3","rate"=>65)
);
for($i=0;$i<sizeof($arr1);$i++){
$count=0;
for($j=0;$j<sizeof($arr2);$j++){
if($arr1[$i]->name == $arr2[$j]->name){
$count++;
}
}
if($count==0){
array_push($arr2,(object)array("name"=>$arr1[$i]->name,"rate"=>$arr1[$i]->rate));
}
}
print_r($arr2);
?>
Doesn't need to be complicated, assuming that you allow the arrays to contain objects of the same type and structure. We don't have enough context given the question to understand whether there is a good reason you can't.
//$array1 original array
//$array2 target array
$array2 = array_merge($array1, $array2);
I have the following array (just a part of the complete array) and I want to extract the value of [cat_ID].
Array ([1] => stdClass Object ( [term_id] => 21 [name] => z_aflyst [slug] => z_aflyst
[term_group] => 0 [term_taxonomy_id] => 23 [taxonomy] => category
[description] => [parent] => 0 [count] => 1 [object_id] => 7 [cat_ID] => 21
[cat_name] => z_aflyst ))
So I need to extract the 21 in this case. However, I only want to extract the cat_ID if the cat_name equals z_aflyst.
Give that you have an array of objects:
Array (
[1] => stdClass Object
(
[term_id] => 21
[name] => z_aflyst
[slug] => z_aflyst
[term_group] => 0
[term_taxonomy_id] => 23
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[object_id] => 7
[cat_ID] => 21
[cat_name] => z_aflyst )
)
foreach ($items as $item)
{
if($item->cat_name == 'z_aflyst')
{
//do stuff
}
}
You have an array of standard objects, which properties can be accessed using the arrow (object) operator ->.
You can use array_filter() to filter out unwanted elements of the array:
// Assuming your array is called $items
$filtered = array_filter($items, function($v) {
return $v->cat_name === 'z_aflyst';
});
After that, you can "flatten" the array using array_map() so that it only contains the cat_ID if you wish:
$filtered = array_map(function($v) {
return $v->cat_ID;
}, $filtered);
This will leave you with a one-dimension, indexed array of cat_IDs.
Your array is in this example a little more than a simple array, is a standard object. And you can take advantage of this. You can the properties of a standard object by this formula:
$object->property;
in your case the object is
$object = $array[1];
or by this formula as an array
$array[key];
in your case to get the value of cat_ID:
$object->cat_ID;
So your code will be something like:
if ($object->cat_name == 'z_aflyst') {
// do stuff with your cat_ID value
echo $object->cat_ID;
}
// will echo 21 only of the cat_name has value 'z_aflyst'
iam trying to sort this array by array[key]['premium']['Monthly'] and if there are two Monthly prices the same, then sort by quarterly, then semi-annual, then annual.
i search and couldnt figure out how to use array_multisort function.
Array (
[0] => Array (
[product_id] => 1
[rate] => 27.07
[premium] => Array (
[Annual] => 436.05
[Semi-Annual] => 226.75
[Quarterly] => 115.6
[Monthly] => 37.11
)
)
[1] => Array (
[product_id] => 2
[rate] => 35.00
[premium] => Array (
[Annual] => 565
[Semi-Annual] => 293.8
[Quarterly] => 149.73
[Monthly] => 50.85
)
)
[2] => Array (
[product_id] => 3
[rate] => 30.52
[premium] => Array (
[Annual] => 497.8
[Monthly] => 47.29
)
)
)
I think you want to use usort function, something like
function compare($a, $b){
$p1 = $a["premium"];
$p2 = $b["premium"];
if($p1["Monthly"] == $p2["Monthly"]){
// compare by quarterly
...
}else{
if($p1["Monthly"] < $p2["Monthly"])then return -1;
else return 1;
}
}
usort($prices, "compare");
where $prices is your array. The comparision function isn't implemented fully, just to show the idea. Also, since it looks like there might be missing items in the price array (ie last one misses Quarterly and Semi-Annual) you have to check first (before comparison) does the items exists and take appropriate action in case one or both are missing.
I am currently stumped while searching for an answer, but I have an array which contains information relating to a tournament, as seen below.
I would like to search through this Array of arrays for specifically the opponent key, and determine if they are all -2. This is because the logic is that -2 is a bye, so if all people have -2 as their opponent, this means that all brackets have been finished.
My initial thought was just do an array_search(!(-2), $anArray), but that obviously didn't work and I hit myself on the head for thinking it would be that easy haha. Thanks.
EX:
Array (
[0] => Array ( [dId] => 11 [uId] => 3 [id] => 1 [round] => 0 [opponent] => 3 [bracket] => 0 )
[1] => Array ( [dId] => 11 [uId] => 5 [id] => 2 [round] => 0 [opponent] => -2 [bracket] => 1 )
[2] => Array ( [dId] => 11 [uId] => 10 [id] => 3 [round] => 0 [opponent] => 1 [bracket] => 0 ) )
This function will return true if all opponents are -2 and false if there is a single opponent != -2:
function all_opponent_search($arr){
for($i = 0; $i < count($arr); $i++)
if($arr[$i]['opponent'] != -2)
return false;
return true;
}
how about:
foreach ($masterArray as $subArray) {
if (isset($subArray['opponent']) && ($subArray['opponent'] == -2)) {
// do whatever you need
}
}