I have an array that looks like this when I use var_dump:
array(4) {
[0]=> array(2) {
[0]=> string(1) "1"
["userID"]=> string(1) "1"
}
[1]=> array(2) {
[0]=> string(1) "2"
["userID"]=> string(1) "2"
}
[2]=> array(2) {
[0]=> string(1) "1"
["userID"]=> string(1) "1"
}
[3]=> array(2) {
[0]=> string(1) "1"
["userID"]=> string(1) "1"
}
}
That is 1,2,1,1
I tried using array_unique($arr) but on this particular array, instead of turning it into 1,2, it just turns the array into 1.
It should work, but I'm not sure why it doesn't.
array_unique only removes elements that are equal by their string value. That is not the case for sub-arrays.
You will need to iterate over the array manually (after sorting with a user function) and unset the doubles. Not pretty, sorry.
I am going to guess that all you care about is knowing which userIDs exist in the result set. Therefore, I will flatten the array first. After doing so, I can apply array_unique to obtain only the unique values. As others have stated, array_unique is not designed to work with multidimensional arrays.
$flattened = array_map(
function($e) { return $e['userID']; },
$array
);
$unique = array_unique($flattened);
If you like foreach loops, then it would look like this.
$flattened = array();
foreach ($array as $v) {
$flattened[] = $v['userId'];
}
$unique = array_unique($flattened);
There is also an alternative to finding unique elements which offers a performance boost over array_unique -- O(n) time complexity versus O(nlogn). That is, array_unique($array) is equivalent to array_keys(array_flip($array)).
A kind of quick and dirty method might be to iterate over all elements, serialize the values and use these as keys in a new array that contains their values as well then use array_values() on that array like this:
<?php
function array_unique_recursive(array $a) {
$result = array();
foreach ($a as $item)
$result[serialize($item)] = $item;
return array_values($result);
}
?>
<?php
$arr = array(
array ( 0=>"1",
userID=>"1"),
array ( 0=>"2",
userID=>"2"),
array ( 0=>"1",
userID=>"1"),
array ( 0=>"1",
userID=>"1"));
$arr_unique=array_unique($arr);
echo '<pre>';
var_dump($arr_unique);
echo '</pre>';
?>
Try using sort regular filter ...
<?php
$arr = array_unique($arr, SORT_REGULAR);
?>
Related
I have 2 arrays I want to get the values that are not the same but for some reason this is not working:
$newArray = array_unique(array_merge($array1, $array2)
var_dump(array1) = array(3) { [0]=> string(17) "verbal aggression" [1]=> string(19) "physical aggression" [2]=> string(3) "vol" }
var_dump(array2) = array(2) { [0]=> string(17) "verbal aggression" [1]=> string(19) "physical aggression" }
So I suspect $newArray to be:
array(1) { [0]=> string(3) "vol"" }
array_diff — Computes the difference of arrays
$array1 = array("verbal aggression", "physical aggression", "vol");
$array2 = array("verbal aggression", "physical aggression");
$result=array_diff($array1,$array2);
print_r($result);
Output :
Array
(
[2] => vol
)
If you want the difference between two arrays you can use array_diff as suggested by #Sunil. But that finds only the elements that are in $array1 but not in $array2.
If you want to find differences use the function below. This will also find elements that are in $array2 but not in $array1
function differences($array1, $array2){
return array_merge(array_diff($array1,$array2),array_diff($array2,$array1));
}
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 7 months ago.
halo everyone. now I'm trying to merge array inside array after query from SQL.. and the result like this
array(3) {
[0]=>
array(1) {
["building_id"]=>
string(1) "1"
}
[1]=>
array(1) {
["building_id"]=>
string(1) "2"
}
[2]=>
array(1) {
["building_id"]=>
string(1) "3"
}
}
I already tried to use this code
$result=[];
foreach($bulding_ids as $arr)
{
$result = array_merge($arr['building_id'],$result);
}
but maybe that is not a answer
I want to that array become like this
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
Can I make like that?
You could just use array_column().
$result = array_column($building_ids, 'building_id');
array_column() returns the values from a single column of the input,
identified by the column_key. Optionally, an index_key may be
provided to index the values in the returned array by the values from
the index_key column of the input array.
This eliminates the need for a loop.
Output:
array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" }
The only downside of this, is that all of the building ID's will be stored as strings. If this is a problem for your application, you can easily use array_map() to convert them to ints.
Directly after the line above, do this:
$result = array_map('intval', $result);
array_map() returns an array containing all the elements of array1
after applying the callback function to each one. The number of
parameters that the callback function accepts should match the number
of arrays passed to the array_map()
Output:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
You can also make this a single line solution:
$result = array_map('intval', array_column($building_ids, 'building_id'));
But in my opinion this looks a bit more messy.
You need to parse every element in your first array and return the id. Then you convert it into int type. Finally, you save the new value into a new array.
<?php
$bulding_ids[] = ["Building_id" => "1"];
$bulding_ids[] = ["Building_id" => "2"];
$bulding_ids[] = ["Building_id" => "3"];
$result = array();
foreach($bulding_ids as $val){
$result[] = (int)$val['Building_id'];
}
var_dump($result);
I want to get the sum of all the values in array in php. Here I have array
$_SESSION['price'][];
I have some values in the array which has been inserted in to array in each iteration.
when do var_dump($_SESSION['price']); of array I am getting
array(1) { [0]=> string(4) "4806" } array(1) { [0]=> string(5) "65000" } array(1) { [0]=> string(5) "44005" } array(1) { [0]=> string(6) "215668" } array(1) { [0]=> string(4) "7896" }
now I want to calculate each value i.e 4806+ 65000+44005+215668+7896
How can I do this?
I tried echo "totalsum".array_sum($_SESSION['cart_total']);
but I got the output
totalsum4806totalsum65000totalsum44005totalsum215668totalsum7896
You can simply use array_sum like as
echo array_sum(call_user_func_array('array_merge', $arr));
Or for PHP > 5.5.0 You can also use array_column like as
echo array_sum(array_column($arr,0));
Output:
337375
Demo
Apparently you have a 2-dimensional array. Every element of $_SESSION['price'] is an array with one element, rather than a price. I'm not sure why you did it that way, but you'll need to write a loop to access them.
$sum = 0;
foreach ($_SESSION['price'] AS $subarray) {
$sum += $subarray[0];
}
Maybe you should fix whatever is creating the session variable so it makes it a 1-dimensional array. The sub-arrays don't seem to serve any purpose.
Try this: I've manipulated your array
$arr = $_SESSION['price'];
foreach($arr as $key => $val)
{
$newVal[] = $val[0];
}
print_r(array_sum($newVal)); //output is 337375
Normally, you would sum an array like this:
$sum = array_sum($_SESSION['price']);
However, this will not work for you for two reasons:
Your values are not stored as integers, but as strings (hence the " in the var dump). (OK, array_sum might convert it to an integer for you, so perhaps this is not a problem in practice.)
Your values are not stored as elements in the array, but for some reason as single elements in a sub array (hence the array(1) { [0]=> in the var dump).
If there are no reasons to why you would want to have it like that, the easiest solution would be to just fix those two things when the array is created, so instead of a nested array of strings you have a flat array of integers.
If that is not possible for some reason, you can sum it like this:
$sum = 0;
foreach($_SESSION['price'] as $e) {
// Convert the first element of the sub array to integer and add it to the $sum.
$sum += (int)$e[0];
}
I think you use $_SESSION['cart_total'], but you have to use like $_SESSION['price']. When the code is like below
$a = array("price" => array("4806", "65000", "44005", "215668", "7896"));
var_dump($a["price"]);
echo "<br>";
echo "totalsum = " . array_sum($a["price"]);
The output will look like below
array(5) { [0]=> string(4) "4806" [1]=> string(5) "65000" [2]=> string(5) "44005" [3]=> string(6) "215668" [4]=> string(4) "7896" }
totalsum = 337375
OR
$a["price"][] = array("4806");
$a["price"][] = array("65000");
$a["price"][] = array("44005");
$a["price"][] = array("215668");
$a["price"][] = array("7896");
$sum = 0;
foreach ($a["price"] AS $price) {
$total += $price[0];
}
echo $total;
Can anybody help me out, I'm stuck, don't know how to write a php nested for loop to convert into a key value array.
This is the array structure.
Needed to turn into key value array( combining JobDescription and userdetail array together)
array(2) {
["jobDescription"]=> array(5) {
["funeralFor"]=> string(6) "Myself"
["serviceType"]=> string(1) "1"
["religionType"]=> string(1) "2"
["area"]=> string(4) "2154"
["customerComment"]=> string(6) "fdfddf"
}
["userDetail"]=> array(6) {
["contactEmail"]=> string(16) "fdddf#fffgfg.com"
["contactFirstName"]=> string(6) "fddfdf"
["contactLastName"]=> string(6) "fddffd"
["contactPhoneNumber"]=> string(10) "0420988191"
["signup"]=> array(2) {
["id"]=> string(32) "8048f0f7106c336e1a8825d1d3bec902"
["input"]=> string(3) "k5m"
}
["agreement"]=> string(1) "1"
}
}
Thanks so much in advance
You have two arrays stored in an array. You want the values of both arrays under one array instead of two subarrays?
$newArray = array_merge($array['jobDescription'], $array['userDetail']);
I think you're looking for array_merge, which merges two arrays together:
$new_arr = array_merge($arr['jobDescription'], $arr['userDetail']);
array_merge($bigArray['jobDescription'], $bigArray['userDetail']);
You only need to loop once. No need for nesting. This solution covers where you have an undefined number of arrays to combine. Otherwise, you can use array_merge as suggested by Dickie
$allValues = array();
if(count($mainArray) > 0)
{
foreach($mainArray as $arr)
{
$allValues += $arr;
}
}
The array_merge() function can create an array from multiple arrays. In your example, it works this way:
$yours = array(...);
$values = array_merge($yours["jobDescription"], $yours["userDetail"]);
I've got two arrays, for which var_dump give the following values:
$array1:
Artifacts:array(2) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } [1]=> array(3) { [0]=> string(7) "module2" [1]=> string(17) "path/to/file2.txt" [2]=> string(0) "" } }
$array2:
Artifacts:array(1) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } }
I would think that doing array_diff($array1,$array2) would give me an array countaining only the second elements. Instead I got an empty array. I try switching the parameters, and still an empty_array, but this time without surprise. Wouldn't array_diff work on arrays of arrays?
From the documentation:
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
echo (string) array(); gives you just Array, so for array_diff, your arrays look like:
$array1 = array('Array', 'Array');
$array2 = array('Array');
So to create a diff for your arrays, you would need something like this (assuming that every element in the arrays is itself an array):
$diff = array();
foreach($array1 as $val1) {
$contained = false;
foreach($array2 as $val2) {
if(count(array_diff($val1, $val2)) == 0) {
$contained = true;
break;
}
}
if(!$contained) {
$diff[] = $val1;
}
}
Disclaimer: This is more or less just a sketch.
From the array_diff documentation.
This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);
From the array_diff manual page: "This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);."
Asked and answered here:
recursive array_diff()?