Count duplicate numbers inside of foreach - php

Basically, I am fetching data from an API and that API has duplicate numbers. I want to count the duplicate numbers within the foreach, but its not working for some reason. I am not sure what I am doing wrong. You can see there is 33 many times. See the picture how it prints. It should be showing something like this
Array
(
[33] => 5
[2] => 3
)
Code:
foreach ($parsed_json1->numbers as $item) {
$ui = $item->no;
$currentp= number_format($ui, 6);
//echo $currentp;
//echo "</br>";
$array = array($currentp);
$vals = array_count_values($array);
//echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);
}

The fundamental flaw of your code is that you take one value and format it, then you put it into array and then do array_count_values on it.
See the difference:
$arr = [33, 32, 23, 33, 22, 23, 32, 33, 33];
print_r(array_count_values($arr));
foreach($arr as $a) {
$currentp= number_format($a, 6);
$array = array($currentp);
$vals = array_count_values($array);
print_r($vals);
}
First print_r prints:
Array
(
[33] => 4
[32] => 2
[23] => 2
[22] => 1
)
And the print_r inside foreach prints:
Array([33.000000] => 1)
Array([32.000000] => 1)
Array([23.000000] => 1)
Array([33.000000] => 1)
Array([22.000000] => 1)
Array([23.000000] => 1)
Array([32.000000] => 1)
Array([33.000000] => 1)
Array([33.000000] => 1)
Do you realize the difference?
I guess, what you need is
$arr = (array_count_values([33, 32, 23, 33, 22, 23, 32, 33, 33]));
$new_arr = [];
foreach($arr as $k => $a) {
$new_arr[number_format($k, 6)] = $a;
}
print_r($new_arr);
Which outputs:
Array
(
[33.000000] => 4
[32.000000] => 2
[23.000000] => 2
[22.000000] => 1
)

Not sure why you use number_format(), but I'm guessing you need something like this
$num_array = []; // Initialize number array
foreach ($parsed_json1->numbers as $item) {
$ui = $item->no;
$currentp= number_format($ui, 6);
$num_array[] = $currentp; // Store each number first to number array
}
// After foreach loop, do array_count_values to number array
$vals = array_count_values($num_array);
print_r($vals); //Print result

Related

Basic Array Referencing Php

How can I reference the following dynamic arrays' elements ?
$log = array();
$arr1 = array ('a'=>'6:16pm','b'=>2,'c'=>3,'d'=>4,'e'=>5);
$arr2 = array ('a'=>'6:24pm','b'=>20,'c'=>30,'d'=>40,'e'=>50);
$log = array_merge($log, array($arr1['a']=>$arr1));
$log = array_merge($log, array($arr2['a']=>$arr2)); //<-- to use time as key
print_r($log);
for ($x = 0; $x < count($log); $x++) {
print_r ($log[0][$x]['a']); // <-- referencing issue Undefined offset: 0 .. line 20
}
//------ produces
Array
(
[6:16pm] => Array
(
[a] => 6:16pm
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
[6:24pm] => Array
(
[a] => 6:24pm
[b] => 20
[c] => 30
[d] => 40
[e] => 50
)
)
I'm pretty sure it has something to do with the way I'm naming the $log main array.. and there's probably a better way to do what I wish(.. add/ new elements to $log using the time key) - Still a php noob unfortunately. Thanks for any pointers.
It's a little unclear, but just create an array from the two and use the a index:
$log = array($arr1, $arr2);
foreach($log as $values) {
echo $values['a']; // 6:16pm
}
Or if you want the time as the index, then re-index on a:
$log = array($arr1, $arr2);
$log = array_column($log, null, 'a');
foreach($log as $time => $values) {
echo $time; // 6:16pm
echo $values['b']; // 2
}
It's prettier, but there is no need for the time as the index unless you are going to use ksort or access by index:
echo $log['6:16pm']['b'];
in cases that you don't know your key is recommended that you use foreach statement:
$logs = array();
$arr1 = array ('a'=>'6:16pm','b'=>2,'c'=>3,'d'=>4,'e'=>5);
$arr2 = array ('a'=>'6:24pm','b'=>20,'c'=>30,'d'=>40,'e'=>50);
$logs = array_merge($logs, array($arr1['a']=>$arr1));
$logs = array_merge($logs, array($arr2['a']=>$arr2)); //<-- to use time as key
$logs = array();
$arr1 = array('a' => '6:16pm', 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$arr2 = array('a' => '6:24pm', 'b' => 20, 'c' => 30, 'd' => 40, 'e' => 50);
$logs = array_merge($logs, array($arr1['a'] => $arr1));
$logs = array_merge($logs, array($arr2['a'] => $arr2)); //<-- to use time as key
foreach ($logs as $time => $log) {
//index:
print_r($time);
//array:
print_r($log);
// a array key:
print_r($log['a']);
//go through all keys:
foreach ($log as $letter => $value) {
//index:
print_r($letter);
//value: a
print_r($value);
}
}
You can not call array like
print_r ($log[0]);
Because your array has key. which is 6:16pm for first one and 6:24pm for second. you have to call it by key name you have assigned. your array should be called like this in everywhere even in loop
print_r ($log["6:16pm"]);

Filter 2d array to keep all rows which contain a specific value

I have a two dimensional haystack array like this:
[
4 => [0, 1, 2, 3, 10],
1 => [0, 1, 2, 3, 10],
2 => [0, 1, 2, 3],
3 => [0, 1, 2, 3]
]
Let's say that I have a search value of $x = 10.
How can I search in above array and get an array index which contains $x.
In my current example, subarrays with key 4 and 1 contain value of $x -- I need those 2 subarrays.
You could loop then use array_search()
$array = array(...); // Your array
$x = 10;
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
echo 'Found on Index ' . $key . '</br>';
}
}
Or if you need the arrays with those index
$array = array(...); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
$result[] = $array[$key]; // push to result if found
}
}
print_r($result);
You can use array_filter() to keep only the array that contains the value you want:
$array = array(
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3),
array(0, 1, 2, 3)
);
$x = 10;
$out = array_filter($array, function($arr) use($x) {
return in_array($x, $arr);
});
print_r($out);
Output:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
)
You can use as well in_array
$array = array(); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (in_array($x, $value)) {
$result[] = $array[$key]; //
}
}
print_r($result)
You can use array_search() function to search the value in array..
Link: http://php.net/manual/en/function.array-search.php
For Exp:
$x = 10; // search value
$array = array(...); // Your array
$result = array(); // Result array
foreach ($array as $key => $value)
{
if (array_search($x, $value))
{
$result[] = $array[$key]; // push the matched data into result array..
}
}
print_r($result);
You can use array_search();
doc: http://www.php.net/manual/en/function.array-search.php

Getting specidic values from PHP arrays

Is there a way to get the first value from array, then the first value key + 3 ; then +6 then + 9 ans so on
Take this array for example,
array(1,2,5,14,19,2,11,3,141,199,52,24,16)
i want extract a value every 3 so the result would be
array(1,14,11,199,16)
Can i do that with existing PHP array function?
Use a for loop and increment the counter variable by 3.
for ($i = 0; $i <= count(your array); $i+3) {
echo $myarray[i]
}
The following is function that will handle extracting the values from a given array. You can specify the number of steps between each value and if the results should use the same keys as the original. This should work with regular and associative arrays.
<?php
function extractValues($array, $stepBy, $preserveKeys = false)
{
$results = array();
$index = 0;
foreach ($array as $key => $value) {
if ($index++ % $stepBy === 0) {
$results[$key] = $value;
}
}
return $preserveKeys ? $results : array_values($results);
}
$array = array(1, 2, 5, 14, 19, 2, 11, 3, 141, 199, 52, 24, 16);
$assocArray = array('a' => 1, 'b' => 2, 'c' => 5, 'd' => 14, 'e' => 19, 'f' => 2, 11, 3, 141, 199, 52, 24, 16);
print_r(extractValues($array, 3));
print_r(extractValues($array, 3, true));
print_r(extractValues($assocArray, 5));
print_r(extractValues($assocArray, 5, true));
?>
Output
Array
(
[0] => 1
[1] => 14
[2] => 11
[3] => 199
[4] => 16
)
Array
(
[0] => 1
[3] => 14
[6] => 11
[9] => 199
[12] => 16
)
Array
(
[0] => 1
[1] => 2
[2] => 52
)
Array
(
[a] => 1
[f] => 2
[4] => 52
)
Use a loop and check the key.
$result = array();
foreach($array as $key => $value) {
if ($key % 3 === 0) {
$result[] = $value;
}
}
Try below one:
<?php
$your_array = array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$every_3 = array();
$i = 0;
foreach($your_value as $value) {
$i++;
if($i%3==0){
$every_3[]=$value;
}
}
var_dump($every_3);
?>
Do like this
$arr=array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$narr=array();
for($i=0;$i<count($arr);$i=$i+3){
$narr[]=$arr[$i]
}
print_r($narr);
<?php
$mynums = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
foreach ($mynums as $key => $value) {
if ( $key % 3 === 0)
{
$newnum[] = $value;
}
}
var_dump($newnum);
?>
$data = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
$matches = array();
foreach($data as $key => $value)
{
if($key%3 === 0)
{
$matches[] = $value;
}
}
var_dump($matches);
The only way you could do it would be to use a loop, count the length of an array, and loop through using a % mathmatical operator.
It gives you a remainder of a division: http://au2.php.net/operators.arithmetic

Remove random items from PHP array

I need to reduce the size of this array to X, so i would like to remove X random items. Here's my PHP array:
Array
(
[helping] => 3
[me] => 2
[stay] => 1
[organized!] => 1
[votre] => 4
[passion,] => 1
[action,] => 1
[et] => 2
[impact!] => 1
[being] => 4
)
I tried array_rand() but it didn't keep the keys/values.
array_rand() returns a random key (or more) of the given array, unset using that:
$randomKey = array_rand($array, 1);
unset($array[$randomKey]);
array_rand() returns an array with keys from your original array.
You would need to delete the keys from your original array using a foreach-loop.
Like this:
// Suppose you need to delete 4 items.
$keys = array_rand($array, 4);
// Loop through the generated keys
foreach ($keys as $key) {
unset($array[$key]);
}
$foo = Array(
"helping" => 3,
"me" => 2,
"stay" => 1,
"organized!" => 1,
"votre" => 4,
"passion," => 1,
"action," => 1,
"et" => 2,
"impact!" => 1,
"being" => 4
);
$max = 5; //number of elements you wish to remain
for($i=0;$i<$max;$i++){ //looping through $max iterations, removing an element at random
$rKey = array_rand($foo, 1);
unset($foo[$rKey]);
}
die(print_r($foo));
Use this,
$array = array(); // Your array
$max = 3;
$keys = array_rand($array, count($array) - $max);
// Loop through the generated keys
foreach ($keys as $key) {
unset($array[$key]);
}
If you need to remove an unknown item number, you can do :
$myArr = [
'helping' => 3,
'me' => 2,
'stay' => 1,
'organized!' => 1,
'votre' => 4,
'passion,' => 1,
'action,' => 1,
'et' => 2,
'impact!' => 1,
'being' => 4,
];
$countToRemove = random_int(1, 2); // can return 1 or 2
$keysToRemove = array_rand($myArr, $countToRemove); // returns an int or array
// create the array to loop
foreach (\is_array($keysToRemove) ? $keysToRemove : [$keysToRemove] as $key) {
unset($myArr[$key]);
}
var_dump($myArr); die();
In this case it will randomly remove 1 or 2 items from the array.

How to do the Array Sorting for only Double Values

I would like to know more about the array sorting. Like we have a example of source:
array(78,124,54,84,124,658,54,84)
here we just want to create another array, with only unique the double values,see in above array 124,54,84 is repeated two times, We only consider these values(we can make any changes for Single Values). And We just want refreshed array like this one:
array(124,54,84)
$values=array_count_values($array);
foreach($values as $key => $val)
{
if ($val >=2)
{
$newarray[]=$key;
}
}
print_r($newarray);
I guess you are looking for this:
$a = array(78, 124, 54, 84, 124, 658, 54, 84);
$counts = array_count_values($a);
$result = array();
foreach ($counts as $key => $value)
{
if ($value == 2)
$result[] = $key;
}
print_r($result);
Output:
Array
(
[0] => 124
[1] => 54
[2] => 84
)

Categories