Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best
Related
I have this array:
Array
(
[one] => Array
(
[a] => 0
[b] => 1
[c] => 1
[d] => 3
[e] => 1
)
[two] => Array
(
[a] => 0
[b] => 3
[c] => 1
[d] => 4
[e] => 1
)
[three] => Array
(
[a] => 3
[b] => 1
[c] => 2
[d] => 4
[e] => 1
)
)
And I want to convert it into single array with the values are the sums of every value inside the inner array, so it could be like this:
Array
(
[a] => 3
[b] => 5
[c] => 4
[d] => 11
[e] => 3
)
How to achieve it?
EDIT
This was the best what I've done:
$rest = array();
foreach($result as $key => $value){
if(is_array($value)) {
foreach($value as $k => $val){
$rest[$k] = array_sum($value);
}
}
}
But it returns all values to be the same, i.e all 9 on every inner key.
You can get the keys from the first child array with array_keys, and then use array_sum and array_column to generate the array of sums.
foreach (array_keys($your_array['one']) as $key) {
$sums[$key] = array_sum(array_column($your_array, $key));
}
array_column does require php >= 5.5.
Incidentally, what you already had was really close to working. If you change
$rest[$k] = array_sum($value);
to
$rest[$k] += $val;
It should be good to go. What you had before was repeatedly summing the entire sub-array and assigning it to each letter key, but you just needed to add the current value to that letter key.
$rest[$k] += $val; will work, but give you undefined index notices for the first sub-array. You can fix that by checking isset before assigning, like this:
$rest[$k] = isset($rest[$k]) ? $rest[$k] + $val : $val;
I would say modifying your original code to work this way would probably be better than redefining array_column if you can't use it.
You have multidimensional Array , that why have to use two loop for understanding in beginning level. First loop will get Every Object of Array , Second Array will get the Params of Object.
$finalArray = array();
for($i = 0;$i<count($array);$i++){ // GET ALL OBJECT FROM ARRAY
foreach($array[$i] as $key=>$value){ // GET ALL KEY FROM OBJECT
$finalArray[$key] += $array[$i][$key];
}
}
print_r($finalArray);
Work on all version of PHP
You can use array_sum and loop over the first dimension
foreach ($array as $key => $values) {
$newArray[$key] = array_sum($values);
}
Credit to Don't Panic's answer above and this answer which is providing array_column() alternative for PHP version < 5.5
// if array_column function don't exist, add array_column function
if (! function_exists('array_column')) {
function array_column(array $input, $columnKey, $indexKey = null) {
$array = array();
foreach ($input as $value) {
if ( ! isset($value[$columnKey])) {
trigger_error("Key \"$columnKey\" does not exist in array");
return false;
}
if (is_null($indexKey)) {
$array[] = $value[$columnKey];
}
else {
if ( ! isset($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not exist in array");
return false;
}
if ( ! is_scalar($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not contain scalar value");
return false;
}
$array[$value[$indexKey]] = $value[$columnKey];
}
}
return $array;
}
}
// sum up the values
$rest = array();
foreach($result as $key => $arr){
if(is_array($arr)) {
foreach($arr as $k => $val){
$rest[$k] = array_sum(array_column($result, $k));
}
}
}
I want to find the Unique values by username:
so the resulting array would be [0] =>JakeP, [1]=>TomC
My code currently works, but I was wondering is there a better way to accomplish this task with less loops, or using array_unique function?
Array
(
[0] => Array
(
[ID] => 3
[Username] => TomC
[Project_Name] => Inventory
)
[1] => Array
(
[ID] => 4
[Username] => JakeP
[Project_Name] => Inventory
)
[2] => Array
(
[ID] => 2
[Username] => TomC
[Project_Name] => Stocks
)
[3] => Array
(
[ID] => 1
[Username] => Tomc
[Project_Name] => Stocks
)
)
My code which works is :
$names_filter = array();
foreach($latest_projects as $project)
{
if(empty($names_filter))
{
$names_filter[] = $project['Username'];
}
else {
foreach($names_filter as $key=>$value)
{
if($value == $project['Username'])
{ break; }
else
{
$names_filter[] = $project['Username'];
}
}
}
}
If you're using PHP >= 5.5 you can take advantage of the array_column() function:
$uniqueNames = array_unique(
array_column($myArray, 'Username')
);
Prior to PHP 5.5, you can use:
$uniqueNames = array_unique(
array_map(
function($value) {
return $value['Username'];
},
$myArray
)
);
You can use the in_array function to simplify your code. Example:
$names_filter = array();
foreach($latest_projects as $project)
{
if(!in_array($project['Username'], $names_filter))
{
$names_filter[] = $project['Username'];
}
}
The in_array() function checks for the existence of a value in an array. So the foreach loop will only add a project username to the $names_filter array if it's not in the array. The output should be a list of unique usernames in the $names_filter array.
We can loop through $latest_projects and store each user name to new array ($filter). Since array can't have two elements with same keys, if the key exists it will be overwritten.
$filter = array();
foreach ($latest_projects as $project)
{
$filter[$project['Username']] = 1;
}
$filter = array_keys($filter);
I can't speak to the performance of this over other solutions, but a similar effect can be achieved with the use of array_map and array_unique. It's not as readable either though, which is just as important.
$uniqueUsers = array_unique(array_map(function ($p) { return $p['Username']; }, $latest_projects));
I've created the multidimensional array in the following format
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
When I try to unset an particular array element based on id, after unset i'm getting the array like below.
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
The array element is getting unset, but the next array element doesn't move to the deleted array position.
For unset an array element, I'm using the following code.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
How to solve this issue? Please kindly help me to solve it.
Thanks in advance.
Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);
Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.
http://www.php.net/manual/en/function.array-splice.php
http://php.net/manual/en/function.unset.php
Why do you use $i++ to find an element to unset?
You can unset your element inside foreach loop:
foreach($cartdetails['products'] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);
Why don't you use this???
$id = 9;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}
Hello all,
Array (
[0] => Array ( [id] => 242)
[1] => Array ( [id] => 24)
[2] => Array ( [id] => 234)
[3] => Array ( [id] => 244)
)
Array (
[0] => 24
[1] => 242
[2] => 244
)
When I used print_r(), I got above two arrays. Now, I need to filter two arrays and get uncommon values so my output will be 234
I would guess you mean array_diff, which returns you the set of elements that only exists in one of the arrays. You might have to run it twice however, if you don't know which array is the superset:
$diff = array_merge(array_diff($a1, $a2), array_diff($a2, $a1));
Oh and if the first array is nested like that, convert it first into a value list with $a1 = array_map("current", $a1) or something.
do a a foreach to go through the array, and then use something like in_array to do a test to see if any of the keys within the first array exists
$array3 = array();
foreach ($array1 as $v)
{
if !(in_array($v['ID'], $array2))
{
$array3[] = $v;
}
}
$array3 = array_unique($array3);
$array3 will return a list of non existant ID's (that didn't exist in $array2)
create two arrays with simply all the values in them, and then do
$arrayResult = $array1;
foreach($array1 as $id => $val) {
if !isset($array2[$id]) {
$arrayResult[] = $id;
}
}
foreach($array2 as $id => $val) {
if !isset($array1[$id]) {
$arrayResult[] = $id;
}
}
and then $arrayResult will have all uncommon values!
I have a multidimensional array, the sub-arrays consist of further values, I would like for all sub-arrays that only have one value to be converted into a string. How can I successfully scan through a multidimensional array to get the result?
Below is a small section of the array as it is now.
[1] => Array
(
[name] => Array
(
[0] => Person's name
)
[organisation] => Array
(
[0] => This is their organisation
[1] => aka something else
)
[address] => Array
(
[0] => The street name
[1] => The town name
)
[e-mail] => Array
(
[0] => test#this.site.com
)
)
and here is how I would like it to end up
[1] => Array
(
[name] => Person's name
[organisation] => Array
(
[0] => This is their organisation
[1] => aka something else
)
[address] => Array
(
[0] => The street name
[1] => The town name
)
[e-mail] => test#this.site.com
)
This should do the trick.
function array2string(&$v){
if(is_array($v) && count($v)==1){
$v = $v[0];
}
}
array_walk($array, 'array2string');
Or as a one-liner, since I'm nuts.
array_walk($array, create_function('&$v', 'if(is_array($v) && count($v)==1){$v = $v[0];}'));
EDIT: It looks like that array is an element in a bigger array. You need to put this function inside of a foreach loop.
function array2string(&$v){
if(is_array($v) && count($v)==1){
$v = $v[0];
}
}
foreach($array as &$val){
array_walk($val, 'array2string');
}
Or using my crazy create_function one-liner.
foreach($array as &$val){
array_walk($val, create_function('&$v', 'if(is_array($v) && count($v)==1){$v = $v[0];}'));
}
This should work no matter how deep the array is.
Put this function in your code:
function array2string(&$v){
if(is_array($v)){
if(count($v, COUNT_RECURSIVE) == 1){
$v = $v[0];
return;
}
array_walk($v, 'array2string');
}
}
Then do this:
array_walk($array, 'array2string');
This PHP 5.3 code uses a closure. You can use a named function, too, if you want. It specifically checks for strings, and calls itself for nested arrays.
<?php
array_walk($array, $walker = function (&$value, $key) use (&$walker) {
if (is_array($value)) {
if (count($value) === 1 && is_string($value[0])) {
$value = $value[0];
} else {
array_walk($value, $walker);
}
}
});