How to get final unique array result from multiple array?
I have an array like this:
Array
(
[0] => Array
(
[0] => 8
[1] => 9
[2] => 7
)
[1] => Array
(
[0] => 7
[1] => 8
[2] => 9
[3] => 33
[4] => 21
)
[2] => Array
(
[0] => 11
[1] => 12
[2] => 33
[3] => 21
[4] => 9
[5] => 31
)
)
Expected result:
Array(
[0] => 7
[1] => 8
[2] => 9
[3] => 33
[4] => 21
[5] => 11
[6] => 12
[7] => 31
)
How to do that using php?
In your desired output indexes are same, you never achieve that. because same indexes are over-written by most recent values.
You can get like below:-
$final_array = array_unique(call_user_func_array('array_merge', $array)); //convert multi-dimensional array to single dimensional and remove duplicates
asort($final_array); // sort by value. this is optional
$final_array = array_values($final_array); // re-index final array and this is optional too
echo "<pre/>";print_r($final_array); // print final array
Output:- https://eval.in/752750
This takes three core PHP functions, sort, array_merg, and array_unique:
sort - sorts an array sent in by reference, meaning rather than returning a variable, it changes the order of the array itself.
array_merg - when combines with call_user_func_array will dynamically combine all the arrays together, however many there are.
array_unique - make sure there is only one of each element.
<?php
$arr = [ [8,9,7], [7,8,9,33,21], [11,12,33,21,9,31] ];
$merged = array_unique(call_user_func_array('array_merge', $arr));
sort($merged);
print_r($merged);
?>
Output:
Array
(
[0] => 7
[1] => 8
[2] => 9
[3] => 11
[4] => 12
[5] => 21
[6] => 31
[7] => 33
)
And here's it inside of eval.in:
https://eval.in/752793
This the way
<?php
$arr = [ [8,9,7], [7,8,9,33,21], [11,12,33,21,9,31] ];
$final = array();
foreach($arr as $child){
foreach($child as $value){
$final[] = $value;
}
}
$final = array_unique($final);
print_r($final);
?>
Demo : https://eval.in/752766
Output :
Array
(
[0] => 8
[1] => 9
[2] => 7
[6] => 33
[7] => 21
[8] => 11
[9] => 12
[13] => 31
)
Method #1: foreach loops with isset() that sort values by their first occurrence (Demo)(*this method seems to be the fastest of all)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
foreach($array as $sub){
foreach($sub as $v){
if(!isset($result[$v])){ // only add first occurence of a value
$result[$v]=$v;
}
}
}
var_export(array_values($result)); // re-index and print to screen
// condensed output: array(8,9,7,33,21,11,12,31)
Method #2: assign temporary keys which force value-overwriting to ensure no duplicates (Demo)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
foreach($array as $sub){
foreach($sub as $v){
$result[$v]=$v; // force overwrite because duplicate keys cannot occur
}
}
sort($result); // sort and re-index
var_export($result); // print to screen
// condensed output: array(7,8,9,11,12,21,31,33)
Method #3: array_merge() with splat operator and array_unique() (Demo)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
$unique=array_unique(array_merge(...$array)); // merge all subarrays
sort($unique); // sort and re-index
var_export($unique); // print to screen
// condensed output: array(7,8,9,11,12,21,31,33)
Method #4: unorthodox json_encode() & preg_match_all() (Demo) (Pattern Demo)
$array=[[8,9,7],[7,8,9,33,21],[11,12,33,21,9,31]];
$unique=preg_match_all('~\b(\d+)\b(?!.*\b\1\b)~',json_encode($array),$out)?$out[0]:[];
sort($unique); // sort and re-index
var_export($unique); // print to screen
// condensed output: array(7,8,9,11,12,21,31,33)
I am creating a set of arrays with the following loop:
$assessmentArr = explode("&", $assessmentData);
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
//print_r($resultArr);
}
Which produces the following results:
Array
(
[0] => community-support
[1] => 24
)
Array
(
[0] => money-rewards
[1] => 30
)
Array
(
[0] => status-stability
[1] => 15
)
Array
(
[0] => personal-professional-development
[1] => 32
)
Array
(
[0] => community-support
[1] => 9
)
Array
(
[0] => money-rewards
[1] => 12
)
Array
(
[0] => status-stability
[1] => 16
)
Array
(
[0] => personal-professional-development
[1] => 29
)
I need to combine these into one array, and where the [0] value matches, I need to add the [1] value together.
So I would like the final output to be something like:
Array
(
[community-support] => 33
[money-rewards] => 42
[status-stability] => 31
[personal-professional-development] => 61
)
I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?
Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.
(Add this code in your loop):
if(!isset($result[$resultArr[0]]))
$result[$resultArr[0]] = $resultArr[1];
else
$result[$resultArr[0]] += $resultArr[1];
Then you have your desired array:
print_r($result);
You could do it like this
$assessmentArr = explode("&", $assessmentData);
$finalArr = array();
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
if(array_key_exists($resultArr[1], $finalArr)){
$finalArr[$resultArr[0]] += $resultArr[1];
}else{
$finalArr[$resultArr[0]] = $resultArr[1];
}
}
First check, if the key already exists in the array, if so you add the value to the value in the final array. Otherwise you add the new index to the final array, with the value from resultArr as inital value.
... way too slow :/
Array
(
[0] => Array
(
[0] => 17
[1] => 111
)
[1] => Array
(
[0] => 17
[1] => 10
)
[2] => Array
(
[0] => 20
[1] => 111
)
)
I want to convert this array as:
array
(
[17]=>121
[20]=>111
)
is there any php array function which can do it easily. I know the other way, but want to know if any ready made function can do that or not??
Please Help.
Here I actually wanted to convert
[0] => Array
(
[0] => 17
[1] => 111
)
17 to key and take 111 as value then in next array
[1] => Array
(
[0] => 17
[1] => 10
)
do the same thing get first value 17 as key and add 10 into previous value 111
which is 121 and then
[2] => Array
(
[0] => 20
[1] => 111
)
take 20 as key and assign value 111 to that key so basically, I want first value as a key and second value as value and for all same keys I want to add values as I stated before.
I thought there might be any PHP ready-made function for that as I have seen there are lots of array processing functions available in PHP. Now, I realized there is no any such kind of function available. I can do my own custom code for this purpose but was looking for good logical solution.
No builtin function for that but it is a simple foreach loop. Assume your array is stored in variable $arr;
$return = array();
foreach ($arr as $a) {
$return[$a[0]] += $a[1];
}
echo "<pre>"; print_r($return);
if you are calling multiple times then you can easily write your own function
$arr[0]= array(17,111);
$arr[1]= array(17,10);
$arr[2]= array(20,111);
$return = subArr($arr);
echo "<pre>"; print_r($return);
function subArr($arr) {
$result = array();
foreach ($arr as $a) {
$result[$a[0]] += $a[1];
}
return $result;
}
I know this won't take much time for experts here. But still please help me out
My Array output is like this
Array ( [0] => 1 [1] => 37 [2] => 1035 ) 1
Array ( [0] => 1 [1] => 37 [2] => 1035 ) mystatusmessage1
Array ( [0] => 4 [1] => 37 [2] => 2925 ) 2
Array ( [0] => 4 [1] => 37 [2] => 2925 ) mystatusmessage2
What I would like to get it is in a single string value like this so that I can insert into database.
1,37,1035,1,mystatusmessage1
4,37,2925,2,mystatusmessage2
How can I achieve that. I'm trying to do with foreach but still I'm not able to do it.
Thanks,
Kimz
use implode function to make string from array for example
if you have array like Array('a','b','c');
implode(',',array('a','b','c') )
will return a,b,c as string
here first argument is your glue by which you want to join string
Here you go.
// Original array
$array = array(0 => 1, 1 => 37, 2 => 1035);
// $_POST array
$_POST = array(1,'mystatusmessage1');
// Jump to the end of array
end($array);
// Merge the post with original array
$newArr = array_merge($array,$_POST);
// Impode
echo implode(",",$newArr);
Repeat with other array.
I was using this code, but If I used array_push() it was inserting values with null, I was using array_push to enter values in the array
foreach ($_POST['record_num'] as $check_rec_num) {
if(!in_array($check_rec_num, $_SESSION['selected_record'][$pageno])) {
array_push($_SESSION['selected_record'][$pageno][], $check_rec_num);
}
}
but when I used this it was automatically adding values in the array, without using array_push why is that so?
foreach ($_POST['rec_num'] as $check_rec_num) {
if(!in_array($check_rec_num, $_SESSION['selected_record'][$pageno])) {
$_SESSION['selected_record'][$pageno][] = $check_rec_num;
}
}
1st example
Array ( [1] => Array ( [0] => 36 [1] => 35 ) [2] => )
2nd example (without bar brackets)
Array ( [1] => Array ( [0] => 36 [1] => 35 [2] => 34 ) [2] => Array ( [0] => ) )
Array Design 3rd example without using array_push how the hell it is adding the values automatically at the end of the array without array_push?
Array (
[1] => Array (
[0] => 36
[1] => 35
)
[2] => Array (
[0] => 33
[1] => 32
)
)
You have an extra [] in
array_push($_SESSION['selected_record'][$pageno][], $check_rec_num);
This will do it:
$_SESSION['selected_record'][$pageno] = array();
array_push($_SESSION['selected_record'][$pageno], $check_rec_num);
See the manual on array_push.
Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.
Yet, you should better use $_SESSION['selected_record'][$pageno][] since
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
That's because of the extra []
Remove it and it'll work:
array_push($_SESSION['selected_record'][$pageno], $check_rec_num);