Need to get unique values in array - php

Array
(
)
Array
(
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
)
Array
(
[0] => 14
[1] => 12
)
I want this array
Array
(
[0] => 14
[1] => 12
)
Here is my code:
$colorarray = array();
foreach($catIds as $catid){
$colorarray[] = $catid;
}
Need to get unique array values
Thanks

You can use call_user_func_array with array-merge for flatten your array and then use array-unique as:
$res = call_user_func_array('array_merge', $arr);
print_r(array_unique($res)); // will give 12 and 14
Live example 3v4l
Or as #Progrock suggested: $output = array_unique(array_merge(...$data)); (I like that syntax using the ...)

You can always do something like this:
$colorarray = array();
foreach($catIds as $catid){
if(!in_array($catid, $colorarray) {
$colorarray[] = $catid;
}
}
But also this has n*n complexity, So if your array is way too big, it might not be the most optimised solution for you.

You can do following to generate unique array.
array_unique($YOUR_ARRAY_VARIABLE, SORT_REGULAR);
this way only unique value is there in your array instead of duplication.
UPDATED
This is also one way to do same
<?php
// define array
$a = array(1, 5, 2, 5, 1, 3, 2, 4, 5);
// print original array
echo "Original Array : \n";
print_r($a);
// remove duplicate values by using
// flipping keys and values
$a = array_flip($a);
// restore the array elements by again
// flipping keys and values.
$a = array_flip($a);
// re-order the array keys
$a= array_values($a);
// print updated array
echo "\nUpdated Array : \n ";
print_r($a);
?>
Reference link
Hope this will helps you

I have updated your code please check
$colorarray = array();
foreach($catIds as $catid){
$colorarray[$catid] = $catid;
}
This will give you 100% unique values.

PHP: Removes duplicate values from an array
<?php
$fruits_list = array('Orange', 'Apple', ' Banana', 'Cherry', ' Banana');
$result = array_unique($fruits_list);
print_r($result);
?>
------your case--------
$result = array_unique($catIds);
print_r($result);

You can construct a new array of all values by looping through each sub-array of the original, and then filter the result with array_unique:
<?php
$data =
[
[
0=>13
],
[
0=>13
],
[
0=>17,
1=>19
]
];
foreach($data as $array)
foreach($array as $v)
$all_values[] = $v;
var_export($all_values);
$unique = array_unique($all_values);
var_export($unique);
Output:
array (
0 => 13,
1 => 13,
2 => 17,
3 => 19,
)array (
0 => 13,
2 => 17,
3 => 19,
)

Related

PHP change array structure

I have an existing array in this following structure,
Array
(
[0] => 1
[1] => 3
)
And, I want to convert in the following structure:
Array
(
[0] => Array
(
[class_id] => 1
)
[1] => Array
(
[class_id] => 3
)
)
Any suggestions, please let me know.
Thanks in advance!
Use a map to iterate over the array items and return a new array for each one of them.
<?php
function map($n) {
return [
'class_id' => $n
];
}
$a = array(1, 3);
$b = array_map("map", $a);
print_r($b);
?>
U just need to foreach this like this:
$data = [1, 3];
$result = [];
foreach ($data as $item) {
$result[] = ["class_id" => $item];
}
Seems that is exactly u need )
One liner:
array_walk($data, function(&$n){ $n = ['class_id'=>$n]; })
Keep in mind that we:
Pass the array as a reference to array_walk.
Then we pass each element as a reference to modify its content.
Also, array_walk keeps your index intact.

How can i split array into two array based on integer value

Here is an example array I want to split:
(1428,217,1428)
How do I split it in 2 array like this?
(1428,1428)
(217)
I have tried following way but it's only return 1428 array.
$counts = array_count_values($array);
$filtered = array_filter($array, function ($value) use ($counts) {
return $counts[$value] > 1;
});
One way to solve this for your example data is to sort the array and use array_shift to get the first element of the array and store that in an array.
$a = [1428,217,1428];
sort($a);
$b = [array_shift($a)];
print_r($a);
print_r($b);
Result
Array
(
[0] => 1428
[1] => 1428
)
Array
(
[0] => 217
)
You can try this.
$array = array(1428,217,1428);
$array1 = array_slice($array, 0, 2);
$array2 = array_slice($array, 2, 3);
print_r($array1);
print_r($array2);
And the output will like this:-
Array
(
[0] => 1428
[1] => 217
)
Array
(
[0] => 1428
)
In your case it will only return 1428 since array_count_values returns an array with values as keys and their frequency as array value therefore $counts will be equal to array('1428' => 2, '217' => 1);
If I understood your question well you should do something like this:
$array1 = [1428, 217, 1428];
$result = [];
foreach($array1 as $value){
$result[$value][] = $value;
}
This will not create an array for each different value but will create a new element for each unique value in $result. The final value of $result will be array('1428' => [1428, 1428], '217' => [217]) . Which can be easily manipulated as if they were 2 different arrays.
Let me know if this works for you, if not I will try to update my answer according to your specification.

Sum arrays in array variable

I have a little problem. Here is the code:
$arr = explode(',', $odluka);
$arr2 = array($arr[0], $arr[1], $arr[2], $arr[3], $arr[4], $arr[5], $arr[6], $arr[7], $arr[8], $arr[9]);
while ($arrk = current($arr2)) {
if ($arrk == '1') {
$ark = key($arr2);
//print_r($ark);
//echo $arr2[$ark];
$arop = explode(',', $utroseno);
$aropk = array($arop[0], $arop[1], $arop[2], $arop[3], $arop[4], $arop[5], $arop[6], $arop[7], $arop[8], $arop[9]);
$array = array($aropk[$ark]);
print_r($array);
}
next($arr2);
}
Output of $array is
Array ( [0] => 1 ) Array ( [0] => 5 ) Array ( [0] => 10 ) Array ( [0] => 4 ) Array ( [0] => 4 ) Array ( [0] => 1 ) Array ( [0] => 1 )
How can I merge this values and sum them. I want sum of 1+5+10+4+4+1+1. Thanks!
declare a variable to store sum
iterate over array
-> add value to sum
Here is a simple example how to deal with your output array:
$data = [
[1], [5], [10], [4]
];
$sum = array_sum(array_map(function($elem) { return $elem[0]; }, $data));
var_dump($sum);
You don't need to assign them to another array and loop..you can just sum everything after explode. You just need one line of code for that:
array_sum(explode(',', $odluka));
Then you'll get the sum of all the numbers
Not need using any array and loop.You are using only "array_sum ()" php building function.Like
<?php
$foo[] = "12";
$foo[] = 10;
$foo[] = "bar";
$foo[] = "summer";
echo array_sum ($foo); //same as echo "22";
?>
For more information Read Php Manual link
Use this function
array_sum ($arr);

Count how many times a value appears in this array?

I have this php array named $ids:
Array (
[0] => Array ( [id] => 10101101 )
[1] => Array ( [id] => 18581768 )
[2] => Array ( [id] => 55533322 )
[3] => Array ( [id] => 55533322 )
[4] => Array ( [id] => 64621412 )
)
And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.
Something like this:
$newArr = array(
10101101 => 1,
18581768 => 1,
55533322 => 2,
64621412 => 1,
);
This is what I have:
$newArr = array();
$aux1 = "";
//$arr is the original array
for($i=0; $i<count($arr); $i++){
$val = $arr[$i]["id"];
if($val != $aux1){
$newArr[$val] = count(array_keys($arr, $val));
$aux1 = $val;
}
}
I supose array_keys doesn't work here because $arr has the id values in the second dimension.
So, how can I make this work?
Sorry for my bad english and thanks.
array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.
$newArr = array_count_values(array_column($ids, 'id'));
Or do it by hand like this where $arr is your source array and $sums is your result array.
$sums = array();
foreach($arr as $vv){
$v = $vv["id"];
If(!array_key_exists($v,$sums){
$sums[$v] = 0;
}
$sums[$v]++;
}
You can traverse your array, and sum the id appearance, live demo.
$counts = [];
foreach($array as $v)
{
#$counts[$v['id']] += 1;
}
print_r($counts);

Combine Indexed arrays with the same keys

I am using the Flot jQuery plugin to create a graph on how many visitors there have been per platform. I would like to create a 4th line with total visitors, calculated by previously retrieved data.
I need to combine several multi-dimensional Indexed arrays, but not simply merging them recursively. I.E:
$arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
$arr2 = [[2016/05/04,1],[2016/05/03,3],[2016/05/02,2]];
$arr3 = [[2016/05/04,6],[2016/05/03,7],[2016/05/02,8]];
The output should be:
$arrTotal = [[2016/05/04,9],[2016/05/03,14],[2016/05/02,16]];
How do I accomplish this in a (fairly) simple way?
First of all, you cannot declare your dates the way you did:
$arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
Because it's going to take 2016, divide it by 5 then divide it by 4. You need to put them into quotes.
$arr1 = [['2016/05/04',2],['2016/05/03',4],['2016/05/02',6]];
But to create an associative array, you should do it this way:
$arr1 = array('2016/05/04' => 2, '2016/05/03' => 4, '2016/05/02' => 6);
$arr2 = array('2016/05/04' => 1, '2016/05/03' => 3, '2016/05/02' => 2);
$arr3 = array('2016/05/04' => 6, '2016/05/03' => 7, '2016/05/02' => 8);
Now all you want to do, is loop through each array and sum them up.
$merge = array();
function mergeArray(Array &$merge, Array $array){
// Loop through each key and value
foreach($array as $key => $value)
// Make sure the value is numeric
if(is_numeric($value)){
if(!isset($merge[$key]))
$merge[$key] = $value;
else
$merge[$key] += $value;
}
}
mergeArray($merge, $arr1);
mergeArray($merge, $arr2);
mergeArray($merge, $arr3);
And now if you dump the $merge:
array(3) {
["2016/05/04"]=>
int(9)
["2016/05/03"]=>
int(14)
["2016/05/02"]=>
int(16)
}
Build a method that will sum the values by respecting the keys of existing values.
$arr1 = array('2016/05/04'=>2,'2016/05/03'=>4,'2016/05/02'=>6);
$arr2 = array('2016/05/04'=>1,'2016/05/03'=>3,'2016/05/02'=>2);
$arr3 = array('2016/05/04'=>2,'2016/05/03'=>7,'2016/05/02'=>8);
function array_sum(&$new_arr,$arr) {
foreach ($arr as $date_key => $num_value) {
// initialize date in new array with 0, if not done previously
if (! isset($new_arr[$date_key])) { $new_arr[$date_key] = 0; }
// add number for indexed element of array
$new_arr[$date_key] += $num_value;
}
}
$new_arr = array();
array_sum($new_array,$arr1);
array_sum($new_array,$arr2);
array_sum($new_array,$arr3);
You are trying to sum up every second value from each nested array relatively to their position in the parent array.There's a short and simple solution using array_map, array_sum and array_column functions:
$groupped = array_map(null, $arr1,$arr2,$arr3);
$result = array_map(function($v){
return [$v[0][0], array_sum(array_column($v, 1))];
}, $groupped);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => 2016/05/04
[1] => 9
)
[1] => Array
(
[0] => 2016/05/03
[1] => 14
)
[2] => Array
(
[0] => 2016/05/02
[1] => 16
)
)

Categories