i need to check if there is the name john more than 3 times in the names key within the following array that contains 4 different sub arrays
Array
(
[0] => Array
(
[total] => 4.2
[name] => john
)
[1] => Array
(
[total] => 2
[name] => john
)
[2] => Array
(
[total] => 3
[name] => adam
)
[3] => Array
(
[total] => 1.5
[name] => john
)
)
i was using mysql first but i prefer to use php instead
You can do the following:
$counts = array_count_values(array_column($array,"name"));
Then to check if there's 3 people called "john" :
if (isset($counts["john"]) && $counts["john"] >= 3) {
//Do stuff
} else {
//Do different stuff
}
To find check all peole not called "john" you can either change the above to as #Andreas suggests:
if (isset($counts["john"]) && (count($array) - $counts["john"]) > 3) {
//Do stuff
} else {
//Do different stuff
}
Alternatively do:
$notJohn = count(array_filter($array, function ($element) {
return $element["name" != "john";
}));
if ($notJohn >= 3) ...
A function like this will do the work
I have roughly written it in mobile.
$occurence = 0;
function a() {
for($x = 0; $x < 4; $x++) {
for($y = 0; $y < 2; $y++) {
if (array[$x][$y] === "John") {
$occurence++;
}
}
}
if($occurence > 3) {
return false;
}
else {
return true;
}
}
Here, $namesArray in an array with repeated value in it.Target is to count how many time exist each value in array.
$namesArray =
array("John","Mark","John","Dan","Hasib","Milon","Samad","Milon","John");
$newArray = array();
foreach($namesArray as $name){
if(isset($newArray[$name])){
$newArray[$name]++;
}else{
$newArray[$name] = 1;
}
}
According to code here is output :
Array(
[John] => 3
[Mark] => 1
[Dan] => 1
[Hasib] => 1
[Milon] => 2
[Samad] => 1
)
Related
I will use this function in this loop :
while ($nbrDocument < 12 && $nbrTags > 0)
{
$tmpDocuments = $this
->get('fos_elastica.manager')
->getRepository('AppBundle:Document')
->findFromTag();
$tagPossibilities = $this->generateTagPossibilities($userTags, $nbrTags);
foreach ($tmpDocuments as $document)
{
$present = true;
foreach ($tagPossibilities as $tags)
{
foreach ($tags as $tag)
{
if (!in_array($tag, $document->getTag()))
{
$present = false;
break;
}
}
if ($present) {
break;
}
}
$nbrDocument ++;
array_push($documents, $$document);
}
$nbrTags--;
}
And I need to create the method generateTagPossibilities.
The first parameter contains an array of string data, and the second is the size
of the possibilities I need to have.
For exemple, if I have [1][2][3][4] in my array and $nbrTag = 4, this function should return [1][2][3][4], if $nbrTag = 3, it should return [[1][2][3]] [[1][3][4]] [[2][3][4]] ...
Got any idea of how I can do that ?
You can use the following functions :
function array_hash($a)
{
$s = '';
foreach($a as $v)
{
$s.=$v.'-';
}
return hash('sha256',$s);
}
function removeOne($setList)
{
$returnSetList = array();
$hashList = array();
foreach($setList as $set)
{
foreach($set as $k=>$v)
{
$tmpSet = $set;
unset($tmpSet[$k]);
$hash = array_hash($tmpSet);
if(!in_array($hash, $hashList))
{
$returnSetList[] = $tmpSet;
$hashList[] = $hash;
}
}
}
return $returnSetList;
}
function generateTagPossibilities($userTags, $nbrTags)
{
$aUserTags = array($userTags);
$cUserTags = count($userTags);
if($nbrTags==$cUserTags)
return $aUserTags;
for($i=0; $i<($cUserTags-$nbrTags); $i++)
$aUserTags = removeOne($aUserTags);
return $aUserTags;
}
// Example !
$a = array(1,2,3,4);
print_r(generateTagPossibilities($a,2));
/*
Array
(
[0] => Array
(
[2] => 3
[3] => 4
)
[1] => Array
(
[1] => 2
[3] => 4
)
[2] => Array
(
[1] => 2
[2] => 3
)
[3] => Array
(
[0] => 1
[3] => 4
)
[4] => Array
(
[0] => 1
[2] => 3
)
[5] => Array
(
[0] => 1
[1] => 2
)
)
*/
Im making a tree to store words and an associated number array in php. I need it to look something like this:
Words: apple, ant
[a] => Array
(
[p] => Array
(
[p] => Array
(
[l] => Array
(
[e] => Array
(
[0] => Array
(
[0] => 0
[1] => 0
[2] => 1
[3] => 2
[4] => 3
[5] => 4
)
)
)
)
)
[n] => Array
(
[t] => Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 0
[4] => 0
[5] => 4
)
)
)
)
Of course apple and ant need to share the same [a] index. Im close, but I cant figure out how to properly keep track of the tree index so 'apple' gets into the tree fine but 'ant' is inserted as 'nt'. Heres my code at the moment:
private function insertWordsIntoTree()
{
foreach ($this->words as $word)
{
$characters = preg_replace('/[0-9]+/', '', $words);
$points = $this->getPoints($word);
$this->tree = $this->buildTree($characters, $points, $this->tree);
}
print_r($this->tree);
}
private function buildTree($characters, array $points, array $tree)
{
for ($i = 0; $i < strlen($characters); $i++)
{
$character = $characters[$i];
$remaining_characters = substr($characters, $i + 1);
if (strlen($characters) === 1)
{
$child = [];
$child[$character] = [$points];
return $child;
}
elseif (!isset($tree[$character]))
{
$tree[$character] = $this->buildTree($remaining_characters, $points, []);;
break;
}
else
{
$this->buildTree($remaining_characters, $points, $tree[$character]);
}
}
return $tree;
}
Im pretty sure the problem is at the else statement...I dont think Im keeping track of the current tree index properly. Any help would be much appreciated.
Here's a simple approach that passes the recursion off to php:
$tree = array();
foreach($words as $word) {
$characters = array_reverse(str_split($word));
$temp = array();
foreach($characters as $index => $character) {
if($index == 0) {
$temp[] = getPoints($word);
}
$temp = array(
$character => $temp
);
}
$tree = array_merge_recursive($tree, $temp);
}
I am counting the difference between two days in inside a foreach loop.
foreach ($result as $key => $value) {
# code...
//$temp[$value->user_id]=$value->user_id;
$count_dates=daysBetween($value->user_source_history_added,$current_date);
$tmp_array[$count_dates][] = $count_dates;
}
On debugging tmp_array, I get something like this.
Array
(
[0] => Array
(
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 0
)
[1] => Array
(
[0] => 1
)
[3] => Array
(
[0] => 3
[1] => 3
[2] => 3
[3] => 3
)
)
Now I want to count the number of 0's, 1's, 2's, 3's, etc. So for now there are 7 0's and 1 1's and 4 3's.
How do I get the count of all these numbers and how do I limit it that I get only the count till Array 20??
I tried this:
foreach($tmp_array as $tmp_val)
{
count($tmp_val)
}
But I get the count of main array that is 3
Update if($count_array<=20){}
This is a general solution, it will take in consideration any number in you have in your $temp array and it will store this number as his record in this array
$found_numbers=array();
$results=array();
$count_array=0;
foreach($tmp_array as $first_array)
{ $count_array++;
foreach($first_array as $second_array)
{
if($count_array<=20){
if (in_array($second_array, $found_numbers)) {
$results[$second_array][0]++;
}
else{
array_push($found_numbers,$second_array);
$results[$second_array] = array();
array_push($results[$second_array],1);
}
}
}
}
//to get how many you have number n in your array you have only to type print($results[n][0]);
print($results[0][0]); //will give you 7
print($results[n][0]); //will give the record of the number n in your array
If you want the count of everything added together:
$count = 0;
foreach($tmp_array as $tmp_subarray)
{
foreach($tmp_subarray as $tmp_val) {
if($count < 20) {
$count++;
}
}
}
If you want the amount of 1s, 2s, 3s, etc:
$count = array();
foreach($tmp_array as $tmp_subarray)
{
foreach($tmp_subarray as $tmp_val) {
if($count[$temp_val]) {
$count[$temp_val]++;
} else {
$count[$temp_val] = 1;
}
}
}
This will count all the values of an array no matter how many dimensions assuming the values are arrays or numbers. This will run until the main array has reached $key == 20.
$total = 0;
function addToTotal($number) {
glob $total;
$total = $total + $number;
}
function countArrayValues($array) {
foreach($array as $key => $value) {
if(is_array ($value) {
countArrayValues($value);
} else {
addToTotal($value);
}
}
}
$mainArray; // <-- your array;
foreach($mainArray as $key => $value) {
if($key <= 20) {
countArrayValues($value);
} else {
break;
}
}
echo $total;
Try this :
$array_number_of_numbert = array();
foreach($tmp_array as $tmp_val_num => $tmp_val)
{
$array_number_of_numbert[$tmp_val_num]= $tmp_val;
}
for($i = 0; $i <=20; $i++)
{
if(isset($array_number_of_numbert[$i])) echo count($array_number_of_numbert[$i])." ". $i."'s\n";
}
There is $sFactorGrades which I need to retrieve the 0th element from based on the GradeID and the CommutatorID, which is the 1st and 2nd element in the array respectively.
The GradeID and the CommutatorID is passed as parameters to the function.
The code that I have written is not returning the value which I know is present.
Any recommendations are welcome.
Here is my code:
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
$arraySize = count($sFactorGrades);
for ($i = 0; $i < $arraySize; $i++) {
if (intval($sFactorGrades[i][1]) == $commuatorID && intval($sFactorGrades[i][2]) == $gradeID) {
return $sFactorGrades[i][0];
} else {
return 0;
}
}
}
Here is my data:
Array (
[0] => Array (
[0] => Maximum S Factor
[1] => Commutator ID
[2] => Grade ID
)
[1] => Array (
[0] => 0.6
[1] => 1
[2] => 2
)
[2] => Array (
[0] => 0.6
[1] => 1
[2] => 3
)
[3] => Array (
[0] => 0.6
[1] => 1
[2] => 4
)
)
Here is my result:
0
I suspect the reason for your loop always returning 0 is that you're passing i as the incrementing variable, and not the correct one: $i. Typos can be devastating... If it still doesn't work, feel free to update your post.
Edit: A tip is to insert this at the top of your page while in development stage:
ini_set('display_errors','On');
error_reporting(E_ALL);
In this case, it should give an undefined index error or similar.
The problem with your code is that you return too early. When your code encounters a return statement, it stops the iteration. You need to move the return statement outside the loop to prevent this from happening.
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
$arraySize = count($sFactorGrades);
for ($i = 0; $i < $arraySize; $i++) {
if (intval($sFactorGrades[$i][1]) == $commuatorID &&
intval($sFactorGrades[$i][2]) == $gradeID) {
return $sFactorGrades[$i][0];
}
}
return 0;
}
If your code reached the last return, then it means that the if condition was never satisfied. For getMaximumSFactor (1, 2), this should return 0.2.
Demo
$sFactorGrades[i] need to be $sFactorGrades[$i].
Also it worth to use foreach() instead of normal for().
But thats not all. You need to check all values in array before returning result:
function getMaximumSFactor($commuatorID, $gradeID) {
$sFactorGrades = populateSFactorGrades();
foreach($sFactorGrades as $key=>$value){
if (intval($value[1]) == $commuatorID && intval($value[2]) == $gradeID) {
return $value[0];
}
}
return 0;
}
Let's say I have following array:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 8
)
[2] => Array
(
[0] => c
[1] => 16
)
[3] => Array
(
[0] => d
[1] => 21
)
....
)
Numbers in inner array are generated randomly from range (0, 100) and they don't repeat.
I would like to create a loop, which will iterate from 0 to 100 and check if loop iteration is equal to inner number of above array. Excepted result is array with 100 elements:
Array
(
[0] => const
[1] => a
[2] => const
[3] => const
[4] => const
[5] => const
[6] => const
[7] => const
[8] => b
[9] => const
[10] => const
.
.
[16] => c
[17] => const
.
.
[21] => d
[22] => const
[23] => const
.
.
)
What I need is something like:
for ($i=0; $i < 100; $i++) {
if($i === $name[$i][1]) {
$new_array[] = $name[$i][0];
} else {
$new_array[] = 'const';
}
}
But I can't get it working, thus I need some help.
I am not an English native speaker, so hopefully you understand what I would like to achieve. Thanks for any help.
you need a nested loop like:
for ($i=0; $i < 100; $i++):
$found = false;
foreach($name as $array):
if($array[1] === $i):
$found = true;
$new_array[] = $array[0];
endif;
endforeach;
if(!$found):
$new_array[] = 'const';
endif;
endfor;
The reason it doesn't work is because each time $i is incremented you're trying to make a match in $name[$i], and not checking all of the arrays in $name, the simplest solution I can think of (and to perform the least number of iterations) would be to do something like:
$new_array = array();
foreach ($name as $n) {
$new_array[$n[1]] = $n[0];
}
for ($i=0; $i<100; $i++) {
if (!isset($new_array[$i])) {
$new_array[$i] = 'const';
}
}
ksort($new_array);
So first of all, loop through your $name array, and set up your $new_array with the the key => value pair (eg. [1] => 'a', [8] => 'b'), then in the for loop just check if the key ($i) has already been set, and if not, set it with the value 'const'. Finally, sort the $new_array by its keys.
The number of iterations in this example is count($name) + 100, whereas a nested loop for example would be 100 * count($name).
use
for ($i=0; $i < 100; $i++) {
if($i === $name[$i][1]) {
$new_array[$i] = $name[$i][0];
}
else{
$new_array[$i] = 'const';
}
}
for ($i = 0; $i < count($name); ++$i) {
if ($name[$i][1] === $i) {
$name[$i] = $name[$i][0];
} else {
$name[$i] = 'const';
}
}
Why do u use Identical operator instead of Equal
for ($i=0; $i < 100; $i++) {
if($i == $name[$i][1]) {
$new_array[] = $name[$i][0];
} else {
$new_array[] = 'const';
}
}