I have a table that I need to find "top trusted builder" from, Trusts are separated by " ; ", So I need to pull all the data, explode the usernames, order and count them, and Im stuck on finally outputting the top username form the array, I have posted up the full segment of PHP, because im sure there has to be a much better way of doing this.
<?php
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);
$buildersarray = array();
while($row = $GTB->fetch()) {
$allbuilders = explode(";", $row['builders']);
for($i = 0; $i < count($allbuilders); $i++)
{
$buildersarray[] = $allbuilders[$i];
}
}
echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>
Outputs
Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)
You can return the array from the array_count_values command into a new array called $topbuilders, and then echo out the current (first) record:
$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);
current() will return the first item in an associative array.
Instead of using array_count_values() it would be better to use the names as the key to a frequency array:
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$result = array();
while (($builders = $GTB->fetchColumn()) !== false) {
foreach (explode(";", $builders) as $builder) {
if (isset($result[$builder])) {
$result[$builder]++;
} else {
$result[$builder] = 1;
}
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);
echo "Name = ", key($result), " Count = ", current($result), "\n";
Related
I have the following array:
$array = [2,2,5,2,2];
I would like to get the number which is different from the others, for example all the numbers are 2 except the number 5. So Is there anyway to get the different number using any array method or better solution? My solution is:
$array = [2,2,5,2,2];
$array1 = [4,4,4,6,4,4,4];
$element = -1;
$n = -1;
$count = 0;
for($i=0; $i<count($array1); $i++) {
if($element !== $array1[$i] && $element !== -1 & $count==0) {
$n = $array1[$i];
$count++;
}
$element = $array1[$i];
}
dd($n);
You can use array_count_values for group and count same value like:
$array = [2,2,5,2,2];
$countarray = array_count_values($array);
arsort($countarray);
$result = array_keys($countarray)[1]; // 5
Since you only have two numbers, you will always have the number with the least equal values in second position
Reference:
array_count_values
array_keys
A small clarification, for safety it is better to use arsort to set the value in second position because if the smallest number is in first position it will appear as the first value in the array
Sorting Arrays
You can user array_count_values which returns array with item frequency.
Then use array_filter to filter out data as follow:
$arrayData = [2,2,2,5];
$filterData = array_filter(array_count_values($arrayData), function ($value) {
return $value == 1;
});
print_r($filterData);
Inside array_filter(), return $value == 1 means only get the data with 1 frequency and thus filter out the other data.
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
print $number . ' | ' . ($count > 1 ? 'Duplicate value ' : 'Unique value ') . "\n";
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
UniqueAndDuplicat($array1);
//output: 2 | duplicate value 5 | Unique value
UniqueAndDuplicat($array2);
//output: 4 | duplicate value 5 | Unique value
?>
Use this function to reuse this you just call this function and pass an Array to this function it will give both unique and duplicate numbers.
If you want to return only Unique number then use the below code:
<?php
function UniqueAndDuplicat($array){
$counts = array_count_values($array);
foreach ($counts as $number => $count) {
if($count == 1){
return $number;
}
}
}
$array1 = [2,2,5,2,2];
$array2 = [4,4,4,6,4,4,4];
echo UniqueAndDuplicat($array1); // 5
echo "<br>";
echo UniqueAndDuplicat($array2); // 6
?>
I have an array which is structured like this:
funActivities(array)
0(array)
Activity(array)
id 4
name walks
1(array)
Activity(array)
id 5
name cycling
2(array)
Activity(array)
id 6
name sand pit
and then another like:
activities
0(array)
id 4
name walks
1(array)
id 6
name sand pit
I want to compare the two arrays and end up with an array which only contains the activities from the 1st array which don't appear in the 2nd array. So in this case I'd end up with just cycling in the array. It's in the first array, but not the second.
Whats the best way to do that?
i made a php function that works for you...
i hope this can help. of course there are some things i could do better but for this szenario it works
<?php
$funActivities[0]['Activity']['id'] = 4;
$funActivities[0]['Activity']['name'] = "walks";
$funActivities[1]['Activity']['id'] = 5;
$funActivities[1]['Activity']['name'] = "cycling";
$funActivities[2]['Activity']['id'] = 6;
$funActivities[2]['Activity']['name'] = "sand pit";
$activities[0]['id'] = 4;
$activities[0]['name'] = "walks";
$activities[1]['id'] = 6;
$activities[1]['name'] = "sand pit";
function compareArray($needle,$haystack)
{
$tmpArray = $haystack;
foreach($needle as $n)
{
$s1 = $n['id'].$n['name'];
$count = 0;
foreach($haystack as $h)
{
$s2 = $h['Activity']['id'].$h['Activity']['name'];
if( $s1 == $s2)
{
unset($tmpArray[$count]);
}
$count++;
}
}
return array_values($tmpArray);
}
$arr = compareArray($activities,$funActivities);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>
I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.
Is there a fast way of doing something like this Compare two arrays with the same value but with a different order in PHP?
I have arrays with potentially same data but in different order and I just need to see whether they are identical.
OK, turns out I get back an object and not an array, I guess...
object(Doctrine\ORM\PersistentCollection)#560 (9) etc.
hmm... Would the easiest way perhaps to iterate over the contents of the collection in order to create my own array and then compare like you all suggested?
Just adding code for my final solution
//Find out if container receives mediasync
$toSync = array();
foreach($c->getVideosToSync() as $v) {
$toSync[] = $v->getId();
}
$inSync = array();
foreach($c->getVideosInSync() as $v) {
$inSync[] = $v->getId();
}
$noDiff = array_diff($toSync, $inSync);
$sameLength = count($toSync) === count($inSync);
if( empty($noDiff) && $sameLength ) {
$containerHelper[$c->getId()]['syncing'] = false;
}
else {
$containerHelper[$c->getId()]['syncing'] = true;
}
I solved it the following way:
<?php
$arrayOld=array(
'1'=>'32',
'2'=>'34',
'3'=>'36',
'4'=>'38',
'5'=>'40',
'6'=>'42',
'7'=>'44',
);
$arrayNew=array(
'2'=>'32',
'1'=>'34',
'3'=>'36',
'4'=>'38',
'5'=>'46',
'6'=>'42',
'7'=>'44',
);
/**
* Here we check if there is any difference in keys or values in two arrays
* array_intersect_assoc - returns values that are same in both arrays checking values as well as keys
* array_diff returns the difference between the arrayNew values and those same values in both arrays, returned by array_intersect_assoc
*/
$result = array_diff($arrayNew,array_intersect_assoc($arrayOld, $arrayNew));
print_r($result);
//result is:
Array (
[2] => 32,
[1] => 34,
[5] => 46,
)
/** We can see, that the indexes are different for values 32 and 34
* And the value for index 5 has also changed from 40 to 46
*/
Just get them in a uniform order using sort() & then diff with them with array_diff().
# Set the test data.
$array1 = array(1,2,3,4,9,10,11);
$array2 = array(3,4,2,6,7);
# Copy the arrays into new arrays for sorting/testing.
$array1_sort = $array1;
$array2_sort = $array2;
# Sort the arrays.
sort($array1_sort);
sort($array2_sort);
# Diff the sorted arrays.
$array_diff = array_diff($array1_sort, $array2_sort);
# Check if the arrays are the same length or not.
$length_diff = (count($array1) - count($array2));
$DIFFERENT_LENGTH = ($length_diff != 0) ? true : false;
# Check if the arrays are different.
$ARE_THEY_DIFFERENT = ($array_diff > 1) ? true : false;
if ($DIFFERENT_LENGTH) {
echo 'The are different in length: ' . $length_diff;
}
else {
echo 'They have the same length.';
}
echo '<br />';
if ($ARE_THEY_DIFFERENT) {
echo 'They are different: ' . implode(', ', $array_diff);
}
else {
echo 'They are not different.';
}
echo '<br />';
There is an array :
$ret = array();
... query execution
$ret['cnt'] = $this->db->num_rows(); // total number of database records
$i = 0;
while ( $this->db->next_record() ) { // fetching database records
$ret[$i]["user_id"] = $this->db->f('user_id') ;
$ret[$i]["user_login"] = stripslashes($this->db->f('user_login'));
$i++;
}
Now I want to remove from this array the element whose "user_id" is equal to a particular value :
if ($ret['cnt'] > 0) {
for ($i=0; $i<$ret['cnt']; $i++) {
if ($ret[$i]['user_id'] == $_SESSION[CODE_USER]) {
unset($ret[$i]);
break;
}
}
}
After printing the array I noticed that the element 0 is not in the array , this is what I am expecting. The only problem is now how to rearrange the array elements so that it will be compact again without any hole in its elements because the element 0 is not present ?
Use array_values:
$ret = array_values($ret);
http://php.net/manual/en/function.array-values.php
Or instead of using the 0th index. You could just grab the first element with reset.
http://php.net/manual/en/function.reset.php
array_values is probably the simplest way to reset keys.
if ($ret['cnt'] > 0) {
for ($i=0; $i<$ret['cnt']; $i++) {
if ($ret[$i]['user_id'] == $_SESSION[CODE_USER]) {
$ret = array_slice($ret,$i,1);
break;
}
}
}
array_slice will also strip away a section of the array and re-index as necessary.