Array difference for multidimensional array with single array in php - php

I want difference of multidimensional array with single array. I dont know whether it is possible or not. But my purpose is find diference.
My first array contain username and mobile number
array1
(
array(lokesh,9687060900),
array(mehul,9714959456),
array(atish,9913400714),
array(naitik,8735081680)
)
array2(naitik,atish)
then I want as result
result( array(lokesh,9687060900), array(mehul,9714959456) )
I know the function array_diff($a1,$a2); but this not solve my problem. Please refer me help me to find solution.

Try this-
$array1 = array(array('lokesh',9687060900),
array('mehul',9714959456),
array('atish',9913400714),
array('naitik',8735081680));
$array2 = ['naitik','atish'];
$result = [];
foreach($array1 as $val2){
if(!in_array($val2[0], $array2)){
$result[] = $val2;
}
}
echo '<pre>';
print_r($result);
Hope this will help you.

You can use array_filter or a simple foreach loop:
$arr = [ ['lokesh', 9687060900],
['mehul', 9714959456],
['atish', 9913400714],
['naitik', 8735081680] ];
$rem = ['lokesh', 'naitik'];
$result = array_filter($arr, function ($i) use ($rem) {
return !in_array($i[0], $rem); });
print_r ($result);

The solution using array_filter and in_array functions:
$array1 = [
array('lokesh', 9687060900), array('mehul', 9714959456),
array('atish', 9913400714), array('naitik', 8735081680)
];
$array2 = ['naitik', 'atish'];
$result = array_filter($array1, function($item) use($array2){
return !in_array($item[0], $array2);
});
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => lokesh
[1] => 9687060900
)
[1] => Array
(
[0] => mehul
[1] => 9714959456
)
)
The same can be achieved by using a regular foreach loop:
$result = [];
foreach ($array1 as $item) {
if (!in_array($item[0], $array2)) $result[] = $item;
}

Related

How to delete array of element in array

I have two array. I want to remove if 2nd array exists in 1st array. For example
array1 = array ("apple","banana","papaya","watermelon","avocado");
array2 = array ("apple","avocado");
I want the output should be
Array ( [1] => banana [2] => papaya [3] => watermelon)
Here are some code that I'd tried.
foreach($array2 as $key){
$keyToDelete = array_search($key, $array1);
unset($array1[$keyToDelete]);
}
print_r($array1);
but the output is
Array ( [1] => banana [2] => papaya [3] => watermelon [4] =>avocado )
It only remove first element.
i also tried to do something like this
$result = array_diff($array1,$array2);
print_r($result);
but the output is it print all element in array1
Noted: I want the result need to be outside foreach loop
array_diff should be work.
<?php
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$array_diff = array_diff($array1, $array2);
print_r($array_diff);
?>
DEMO
output will be.
Array ( [1] => banana [2] => papaya [3] => watermelon)
You can also try below solution. result will be same.. using in_array Check if first array value not in the second tester that value in the new array 'final_result' for results.
in_array support (PHP 4, PHP 5, PHP 7)
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$final_result = array();
foreach($array1 as $value){
if(!in_array($value, $array2)){
$final_result[] = $value;
}
}
print_r($final_result);
?>
DEMO
With the help of array_filter() we can do it easily. It filters elements of an array using a callback function.
array_filter() iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.
Here we have used use($array2) clause to access the external variable inside callback function. $array2 is needed to filter out $array1.
$array1 = array("apple","banana","papaya","watermelon","avocado");
$array2 = array("apple","avocado");
$array1 = array_filter($array1, function($item) use($array2) { return !in_array($item, $array2); });
print '<pre>';
print_r($array1);
Demo
The fastest way to do this is to create a set(associative array) of elements in $array2 and iterate over $array1 and check if element in $array1 exists in our set or not using isset(). We take advantage of the method/algorithm technique called hashing.
<?php
$array1 = array ("apple","banana","papaya","watermelon","avocado");
$array2 = array ("apple","avocado");
$set = [];
foreach($array2 as $element){
$set[$element] = true;
}
$result = [];
foreach($array1 as $element){
if(!isset($set[$element])){
$result[] = $element;
}
}
print_r($result);
Demo: https://3v4l.org/PcS45

How to merge one or more nested array values having same keys

I'm little bit confuse in this concept
Actually I'm having an array like this
$arr = array("0"=>array("username"=>"username1"),"1"=>array("username"=>"username2"),"2"=>array("username"=>"username3"),"3"=>array("username"=>"username4"));
echo "<pre>";print_r($arr);
$finalArray = call_user_func_array('array_merge', $arr);
echo "<pre>";print_r($finalArray);
Finally from this I'm getting an array like this
Array
(
[username] => username4
)
But I need all the values like as follows
Array
(
[0] => username1
[1] => username2
[2] => username3
[3] => username4
)
How should I do this?..Could someone please help me..
Thank you,
Simple solution using array_column function(available since PHP 5.5):
$result = array_column($arr, 'username');
You can write your own function to get usernames
Try this
<?php
function getUserNames($arr){
$userNames = array();
foreach ($arr as $key => $value){
$userNames[$key] = $value["username"];
}
return $userNames;
}
$arr = array("0"=>array("username"=>"username1"),"1"=>array("username"=>"username2"),"2"=>array("username"=>"username3"),"3"=>array("username"=>"username4"));
echo "<pre>";print_r($arr);
$finalArray = getUserNames($arr);
echo "<pre>";print_r($finalArray);
?>

Merge multiple arrays from one array

How to merge multiple arrays from a single array variable ? lets say i have this in one array variable
Those are in one variable ..
$array = array(array(1), array(2));
Array
(
[0] => 1
)
Array
(
[0] => 2
)
how to end up with this
Array
(
[0] => 1
[1] => 2
)
This is the PHP equivalent of javascript Function#apply (generate an argument list from an array):
$result = call_user_func_array("array_merge", $input);
demo: http://3v4l.org/nKfjp
Since PHP 5.6 you can use variadics and argument unpacking.
$result = array_merge(...$input);
It's up to 3x times faster than call_user_func_array.
This may work:
$array1 = array("item1" => "orange", "item2" => "apple", "item3" => "grape");
$array2 = array("key1" => "peach", "key2" => "apple", "key3" => "plumb");
$array3 = array("val1" => "lemon");
$newArray = array_merge($array1, $array2, $array3);
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
array_merge can do the job
$array_meged = array_merge($a, $b);
after the comment
If fixed indexs you can use:
$array_meged = array_merge($a[0], $a[1]);
A more generic solution:
$array_meged=array();
foreach($a as $child){
$array_meged += $child;
}
$resultArray = array_merge ($array1, $array1);
$result = array();
foreach ($array1 as $subarray) {
$result = array_merge($result, $subarray);
}
// Here it is done
Something good to read:
http://ca2.php.net/manual/en/function.array-merge.php
Recursive:
http://ca2.php.net/manual/en/function.array-merge-recursive.php
$arr1 = array(0=>1);
$arr2 = array(0=>2);
$merged = array_merge($arr1,$arr2);
print_r($merged);
array_merge is what you need.
$arr = array_merge($arr1, $arr2);
Edit:
$arr = array_merge($arr1[0], $arr1[1]);

Implode an inner array values

An array
Array
(
[0] => Array
(
[Detail] => Array
(
[detail_id] => 1
)
)
[1] => Array
(
[Detail] => Array
(
[detail_id] => 4
)
)
)
Is it possible to use implode function with above array, because I want to implode detail_id to get 1,4.
I know it is possible by foreach and appending the array values,
but want to know whether this is done by implode function or any other inbuilt function in PHP
What about something like the following, using join():
echo join(',', array_map(function ($i) { return $i['Detail']['detail_id']; }, $array));
If you need to use some logic - then array_reduce is what you need
$result = array_reduce($arr, function($a, $b) {
$result = $b['Detail']['detail_id'];
if (!is_null($a)) {
$result = $a . ',' . $result;
}
return $result;
});
PS: for php <= 5.3 you need to create a separate callback function for that
Please check this answer.
$b = array_map(function($item) { return $item['Detail']['detail_id']; }, $test);
echo implode(",",$b);
<?php
$array = array(
array('Detail' => array('detail_id' => 1)),
array('Detail' => array('detail_id' => 4)),);
$newarray = array();
foreach($array as $items) {
foreach($items as $details) {
$newarray[] = $details['detail_id'];
}
}
echo implode(', ', $newarray);
?>

PHP: Turning multidimensional arrays to single dimension arrays

Basically my app is interacting with a web service that sends back a weird multidimensional array such as:
Array
(
[0] => Array
(
[Price] => 1
)
[1] => Array
(
[Size] => 7
)
[2] => Array
(
[Type] => 2
)
)
That's not a problem, but the problem is that the service keeps changing the index of those items, so in the next array the Price could be at 1 instead of 0.
How do I effeciently transform arrays like this into a single dimension array so I can access the variables through $var['Size'] instead of $var[1]['Size']?
Appreciate your help
$result = call_user_func_array('array_merge', $array);
Like this:
$result = array();
foreach($array as $inner) {
$result[key($inner)] = current($inner);
}
The $result array would now look like this:
Array
(
[Price] => 1
[Size] => 7
[Type] => 2
)
I am using laravel's helper: http://laravel.com/api/source-function-array_flatten.html#179-192
function array_flatten($array)
{
$return = array();
array_walk_recursive($array, function($x) use (&$return) { $return[] = $x; });
return $return;
}
function flattenArray($input, $maxdepth = NULL, $depth = 0)
{
if(!is_array($input)){
return $input;
}
$depth++;
$array = array();
foreach($input as $key=>$value){
if(($depth <= $maxdepth or is_null($maxdepth)) && is_array($value)){
$array = array_merge($array, flattenArray($value, $maxdepth, $depth));
} else {
array_push($array, $value);
// or $array[$key] = $value;
}
}
return $array;
}
Consider $mArray as multidimensional array and $sArray as single dimensional array this code will ignore the parent array
function flatten_array($mArray) {
$sArray = array();
foreach ($mArray as $row) {
if ( !(is_array($row)) ) {
if($sArray[] = $row){
}
} else {
$sArray = array_merge($sArray,flatten_array($row));
}
}
return $sArray;
}
I think i found best solution to this : array_walk_recursive($yourOLDmultidimarray, function ($item, $key) {
//echo "$key holds $item\n";
$yourNEWarray[]=$item;
});
If you use php >= 5.6, you may use array unpacking (it's much faster):
$result = array_merge(...$array);
See wiki.php.net on unpacking

Categories