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") );
Related
Trying to sort my array to show the group with meat categoryName to be first element in array. Is there a better way to sort this array than running two for loops?
My array looks like this
Array
(
[0] => Array
(
[categoryId] => C4ye95zr403cx9wqi11eo
[categoryName] => set
[categoryStatus] => true
)
[1] => Array
(
[categoryId] => Cj-v2b7szu3jpph1rvu03
[categoryName] => meat
[categoryStatus] => true
)
I want to rearrange the array by categoryName == meat to be first element in array.
Currently i'm just running two loops to do this.
$temp = array();
foreach($array as $k => $v)
{
if($v['categoryName']=="meat")
{
$temp[] = $menu[$k];
$setEmpty = false;
unset($array[$k]);
}
}
foreach($menu as $k=>$v)
{
$temp[] = $array[$k];
}
You can utilize usort:
usort($array, function ($element) {
return $element['categoryName'] === 'meat' ? 0 : 1;
});
The documentation states the following about the callback:
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
So, in order to push the meat category to the beginning, all you need to do is say that everything else is greater than it.
You can check the fiddle for a test.
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
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
Ok, I have following 'challange';
I have array like this:
Array
(
[0] => Array
(
[id] => 9
[status] => 0
)
[1] => Array
(
[id] => 10
[status] => 1
)
[2] => Array
(
[id] => 11
[status] => 0
)
)
What I need to do is to check if they all have same [status].
The problem is, that I can have 2 or more (dynamic) arrays inside.
How can I loop / search through them?
array_diff does support multiple arrays to compare, but how to do it? :(
Which ever loop I have tried, or my Apache / browser died - or I got completely bogus data back.
You could just put the problem apart to make it easier to solve.
First get all status items from your array:
$status = array();
forach($array as $value)
{
$status[] = $value['status'];
}
You now have an array called $status you can see if it consists of the same value always, or if it has multiple values:
$count = array_count_values($status);
echo count($count); # number of different item values.
Try this code:
$status1 = $yourArray[0]['status'];
$count = count($yourArray);
$ok = true;
for ($i=1; $i<$count; $i++)
{
if ($yourArray[$i]['status'] !== $status1)
{
$ok = false;
break;
}
}
var_dump($ok);
function allTheSameStatus( $data )
{
$prefStatus = null;
foreach( $data as $array )
{
if( $prefStatus === null )
{
$prefStatus = $array[ 'status' ];
continue;
}
if( $prefStatus != $array[ 'status' ] )
{
return false;
}
}
return true;
}
I'm not sure what you want as output but you could iterate through the outer array and create an output array that groups the inner arrays by status:
$outputArray = array();
foreach ($outerArray as $an_array) {
$outputArray[$an_array['status']][] = $an_array['id'];
}
I have this array being sent to my view
Array
(
[0] => stdClass Object
(
[emg_id] => 2
[fkit] => 1
[door] =>
)
)
I would like to count how many elements are empty, NULL, or '0'.
I tried using count but it always returns '1', instead of counting all of the elements, so I can later determine which satisfy my conditions above.
Any ideas what I'm doing wrong?
// number of "null" elements
echo count(array_filter((array) $array[0], 'is_null'));
There are some other is_*()-functions built-in, that may help you for example to count the number of strings (and so on).
To test, if an element is (e.g.) 0, I suggest to use an anonymous function
echo count(array_filter((array) $array[0], function ($item) {
return $item === 0;
}));
The other cases are similar.
loop through them and count.
function loopMe($array, $value) {
$num = 0;
foreach($array as $key=>$val) {
if($val == $value)
$num++;
}
return $num;
}
$ar = array (
array (
"emg_id" => 2
"fkit" => 1
"door" => null));
$num = loopMe($ar[0], null);