How can i compare values within a multidimensional array - php

I am developing a Bio-metric election system but i am facing problem regarding election results.
I got this array after executing a query.
Array
(
[paty1] => Array
(
[NA122] => stdClass Object
(
[count] => 2
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 1
)
)
[party2] => Array
(
[NA122] => stdClass Object
(
[count] => 0
)
[NA2] => stdClass Object
(
[count] => 0
)
[NA56] => stdClass Object
(
[count] => 0
)
)
)
This array is stored in $data and it can have unlimited indexes.
Now if count of [Paty1][NA122] is greater then count of [Party2][NA122] so i will declare Party1 win in NA122 and i have to compare it with n number of indexes.
e.g. there is another index pary3 so firstly I will compare count of [party1][NA122] with [party2][NA122] and then with [party3][NA122] and winner will be the one with greater count . Can you please help me??
Thanks in advance

Try this:
foreach(current($Result) as $Const=>$val){
echo "Winner of Constituency '$Const': ". findWinner($Const,$Result).PHP_EOL;
}
function findWinner($Const, $Result){
$Max = 0;
$Winner = '';
foreach($Result as $Party => $ConstList){
if($ConstList[$Const]->count>$Max){
$Max = $ConstList[$Const]->count;
$Winner = $Party;
}
}
return $Winner;
}
Check live code here:
https://www.tehplayground.com/x5sPu7JxuexOdwU8

So you want to get the party with the max count for a given NA#.
You can use a function like this:
function maxParty($data, $na) {
$max = null;
foreach($data as $party => $values) {
if(is_null($max)) {
$max = $party;
continue;
} else {
if($values[$na]->count > $data[$max][$na]->count) {
$max = $party;
}
}
}
return $max;
}
Then you feed this function with a $data array and the NA# you want to calculate the max party with. For example
$winner = maxParty($data, 'NA122');
It will return the key for the winner party. I.e. "party1"

Do you mean something like this:
<?php
$data=getData();
$maxValue;
$maxKey;
foreach($data as $key => $paty)
if(!isset($maxValue) || $paty->count>$maxValue){
$maxValue=$paty->count;
$maxKey=$key;
}
echo "$maxValue $maxKey";
function getData(){
$a=array();
for($i=1;$i<100;$i++)
$a["paty$i"]=(object) array("count"=>$i);
return $a;
}
?>
Explanation:
getData returns an array like the one you described
foreach($data as $key => $paty) - iterates through the entire array
if ( ) -- checks if the current value is greater than the previous max
If you want to know more about PHP:
foreach, objects, arrays and google

Related

Get multidimensional sub array count in php

I have below type of array, now I want to get count of it's subarray
For example I want to get count key 7 & 8. How to do it ? Any solution for that ? I tried but but no success :(
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 105
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
$date_count = array();
foreach($FeaturedBlogs as $Key=>$date) {
foreach($date as $d) {
$key = array_keys($d); // get our date
// echo $key;echo "<br>";
print_r($d);
$date_count[$key[0]]++;
}
}
Try this....
//Count Sub Array
$final_array = [];
$x = 0;
function countSubArray($data)
{
global $final_array;
global $x;
foreach($data as $key)
{
if(is_array($key))
{
$final_array[$x][0] = "1";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
if(is_object($key))
{
$final_array[$x][0] = "2";
$final_array[$x][1] = json_encode($key);
$final_array[$x][2] = count((array)$key);
$x++;
countSubArray($key);
}
}
}
// Call Function...
countSubArray($arr); // what array you count..
// Display Sub Array Count...
$t_count = 0;
foreach($final_array as $d)
{
if($d[0] == 1)
{
echo "Array Count :".$d[2]." Array : ".$d[1]."<br>";
$t_count++;
}
}
echo "Total Array Count :".$t_count;
output of this example is...
Array
(
[0] => stdClass Object
(
[id] => 4
[Blogdata] => stdClass Object
(
[7] => Array
(
[0] => stdClass Object
(
[blog_id] => 135
)
)
[8] => Array
(
[0] => stdClass Object
(
[blog_id] => 101
)
)
)
)
)
Array Count :1 Array : [{"blog_id":135}]
Array Count :1 Array : [{"blog_id":101}]
Total Array Count :2
Updated Answer
This is going to use a function as it's own callback function. The function will loop through an object or an array and test each element to see if it is another object or array.
If it did find a new object or array, then the function calls itself again to perform the same operations on the element, effectively traversing through your entire array.
When it has found the bottom of each element it will return the value of the counter which was keeping track of how many arrays it came across.
Like so:
function arrayCounter($data){
//At this point we have an array or an object.
//Lets loop across the elements and see if we have any more nested arrays or objects.
foreach($data as $key){
$count = 0;
//Test each element to see if it's an object or an array.
if(is_array($key) || is_object($key)){
//If it is we are going to send the element through another instance of the function.
$count += arrayCounter($key);
}
//If the element is an array we are going to increment the counter.
if(is_array($key)){
$count++;
}
}
return $count;
}
$count = arrayCounter($data);
echo 'Count: ' . $count; //Using your data this will return "2".
Hope it helps!

How to tell if array contains another array

Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best

How to compare 2 arrays for common items in PHP?

I am writing a script to compare the achievements of one player to another in a game. In each of the arrays the id and timestamp will match up on some entries. I have included a sample of one of the start of the 2 separate arrays:
Array
(
[0] => Array
(
[id] => 8213
[timestamp] => 1384420404000
[url] => http://www.wowhead.com/achievement=8213&who=Azramon&when=1384420404000
[name] => Friends In Places Higher Yet
)
[1] => Array
(
[id] => 6460
[timestamp] => 1384156380000
[url] => http://www.wowhead.com/achievement=6460&who=Azramon&when=1384156380000
[name] => Hydrophobia
)
I want to find all of the array items where the id and timestamp match. I have looked into array_intersect but I don't think this is what I am looking for as it will only find items when the entries are identical. Any help much appreciated.
You may use array_intersect_assoc function.
Try something like this:
<?php
$key_match = Array();
//Loop first array
foreach($array as $key => $element){
//Compare to second array
if($element == $array2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
?>
$key_match will be an array with all matching keys.
(I'm at work and havn't had time to test the code)
Hope it helps
EDIT:
Fully working example below:
<?php
$a1["t"] = "123";
$a1["b"] = "124";
$a1["3"] = "125";
$a2["t"] = "123";
$a2["b"] = "124";
$a2["3"] = "115";
$key_match = Array();
//Loop first array
foreach($a1 as $key => $element){
//Compare to second array
if($element == $a2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
var_dump($key_match);
?>
If you want to go on an exploration of array callback functions, take a look at array_uintersect. It's like array_intersect except you specify a function to use for the comparison. This means you can write your own.
Unfortunately, you need to implement a function that returns -1, 0 or 1 based on less than, same as, greater than, so you need more code. But I suspect that it'll be the most efficient way of doing what you're looking for.
function compareArrays( $compareArray1, $compareArray2 ) {
if ( $compareArray1['id'] == $compareArray2['id'] && $compareArray1['timestamp'] == $compareArray2['timestamp'] ) {
return 0;
}
if ( $compareArray1['id'] < $compareArray2['id'] ) {
return -1;
}
if ( $compareArray1['id'] > $compareArray2['id'] ) {
return 1;
}
if ( $compareArray1['timestamp'] < $compareArray2['timestamp'] ) {
return -1;
}
if ( $compareArray1['timestamp'] > $compareArray2['timestamp'] ) {
return 1;
}
}
var_dump( array_uintersect( $array1, $array2, "compareArrays") );

PHP count null or 'new' elements within array

My array is below. What I am trying to do is count the number of nodes in the array have null or 'new' for read_status.
Is there something more sufficient than looping through the array?
Array
(
[0] => Array
(
[id] => 428
[read_status] =>
)
[1] => Array
(
[id] => 427
[read_status] =>
)
[2] => Array
(
[id] => 441
[read_status] => new
)
[3] => Array
(
[id] => 341
[read_status] => read
)
)
So the count should be 3.
you could do
$count = count(array_filter($myArray, function($item){
return $item['read_status'] != 'new';
}));
echo $count;
but I think its more efficient to just loop through it like this:
$count = 0;
foreach($myArray as $item){
if($item['read_status'] != 'new')$count++;
}
echo $count;
There is nothing wrong with looping in the array to do this, it might actually be faster than using a generic method to do it for you. It's simply this :
$count = 0;
foreach ($arrays as $entry)
{
if (!$entry['read_status'] || $entry['read_status'] === "new")
{
$count++;
}
}
echo $count;
I actually improved my SQL by removing the null completely -- so now read_status is either read or new.
IF(feed_read.read_status IS NULL,'new','read') AS read_status
From there, I was able to utilize another SO question in order to count the 'new' elements.
$counted = array_count_values(array_map(function($value){return $value['read_status'];}, $result));
echo $counted['new'];

Sorting an Array of Objects in PHP In a Specific Order

I have two arrays in PHP. The first array ($author_array) is comprised of user_ids in a particular order, like so: (8, 1, 6)
The second array ($user_results) is comprised of an array of objects like so:
Array
(
[0] => stdClass Object
(
[ID] => 1
[user_login] => user1
)
[1] => stdClass Object
(
[ID] => 6
[user_login] => user6
)
[2] => stdClass Object
(
[ID] => 8
[user_login] => user8
)
)
I'd like to "sort" the second array so it's in this order, which matches the order of the values in the first array of (8, 1, 6). So it'd look like this:
Array
(
[0] => stdClass Object
(
[ID] => 8
[user_login] => user8
)
[1] => stdClass Object
(
[ID] => 1
[user_login] => user1
)
[2] => stdClass Object
(
[ID] => 6
[user_login] => user6
)
)
I'm weak on data structures. How could I do this? :-)
Thanks in advance for your help!
-Bob
Use usort and provide a custom comparison function which uses the position of the key in your "ordering" array to determine the sort order, e.g. something like:
function cmp($a, $b)
{
global $author_array;
$pos1=array_search ($a->ID, $author_array);
$pos2=array_search ($b->ID, $author_array);
if ($pos1==$pos2)
return 0;
else
return ($pos1 < $pos2 ? -1 : 1);
}
usort($user_results, "cmp");
I'm not sure whether this will be significantly slower than other examples, but it seems simpler. It may be that you could build the $user_results array as an associative one to start with, using ID as the key, then you can easily do lookups.
$hash = array();
$result = array();
foreach ($user_results as $obj) {
$hash[$obj->ID] = $obj;
}
foreach ($author_array as $id) {
$result[] = $hash[$id];
}
So I had a similar issue, but I was trying to order an object by an array (that wasn't an object). It's just not possible, so here's my workaround:
$sort_array= array(11, 4, 16, 19, 23);
$myobject = sort_categories($myobject)
function cmp($a, $b) {
if ($a->sort_key == $b->sort_key) { return 0; }
return ($a->sort_key < $b->sort_key) ? -1 : 1;
}
function sort_categories($obj) {
global $sort_array;
foreach($obj as $cat) {
$cat->sort_key = 999;
for ($i=0;$i<count($sort_array);$i++) {
if ($sort_array[$i] == $cat->term_id) $cat->sort_key = $i;
}
}
usort($obj,'cmp');
return $obj;
}
I'm looking through the object and adding a new (property?) called "sort_key" which we'll then use to sort on with usort() and cmp(). By default, the new sort_key will be 999 so it gets stuck at the end.
public static function reorganizeBykey ($objects, array $keys){
$results = array();
foreach($keys as $key){
$i=0;
foreach($objects as $object){
if($object->sourceName==$key){
$results[$i] = $object;
}
$i++;
}
}
$others = (array_diff_assoc($objects,$results));
$results = array_merge($results,$others);
return $results;
}
I hope this is helpful – I had to use this to sort an array() by some keys() and then append what doesn't match at the end.

Categories