Comparing 2 Arrays using array_map? - php

I wanted to refrain from using nested foreach in my actual code, so I was thinking of using an array function (correct me if I'm wrong) called array_walk thinking it would replace my code in foreach.
I wanted to compare both of the WHOLE array if they one of them have the same description, but the problem is array_walk only compares the first key/index and does not go through the second index to check. is there other way? I'm just trying to optimize my code
By the way, this code returns both found
<?php $array = array (
'1' => array(
'count' => '1',
'id' => 1,
'description' => 'Bag',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
), );
$bin = array (
'1' => array(
'count' => '1',
'id' => 2,
'description' => 'Bag',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
), );
$b = array_map(function($array, $bin) {
if ($array['description'] == $bin['description']){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin"=>$bin['description']); }, $array, $bin);
var_dump($b);
?>
but this one, the first array doesnt return found, it should return
found because there is a pencil and bag in $bin array updated the code
<?php
$array = array (
'1' => array(
'count' => '1',
'id' => 1,
'description' => 'Bag',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
),
);
$bin = array (
'1' => array(
'count' => '1',
'id' => 2,
'description' => 'Pencil',
),
'2' => array(
'count' => '1',
'id' => 2,
'description' => 'Bag',
),
);
$b = array_map(function($array, $bin)
{
if ($array['description'] == $bin['description']){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin"=>$bin['description']);
}, $array, $bin);
var_dump($b);
?>

Use array_column first to get all of description keys from $array. Then, you can check these values with $bin values.
$desc = array_column($array, 'description');
$b = array_map(function($array, $bin)
{
global $desc;
if (in_array($bin['description'], $desc)){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin" => $bin['description']);
}, $array, $bin);
var_dump($b);

You don't have any expected output in the question but I assume you want to know the difference between them.
In the manual for array_diff there is a code called arrayRecursiveDiff which handles multidimensional arrays and outputs the difference.
var_dump(arrayRecursiveDiff($array, $bin));
function arrayRecursiveDiff($aArray1, $aArray2) {
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
} else {
if ($mValue != $aArray2[$mKey]) {
$aReturn[$mKey] = $mValue;
}
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
This outputs:
array(2) {
[1]=>
array(2) {
["id"]=>
int(1)
["description"]=>
string(3) "Bag"
}
[2]=>
array(1) {
["description"]=>
string(6) "Pencil"
}
}

You can use this.Nevertheless both arrays have different length or the values do not have the same position, This will work :
$bin_desc=array_column($bin,'description');
$b = array_map(function($array)use($bin_desc) {
if (in_array($array['description'],$bin_desc)){
$count = "found";
}else{
$count = "not found";
}
return array("status" => $count, "cart_array" => $array['description'], "bin"=>$array['description']); }, $array);
var_dump($b);

Related

Extracting value from multidimensional array

$arrayDif = array();
$arrayDif[] = array('employer' => $employer,
'comment' => $comment,
'value' => $resultValue);
Filling in from a loop.
Below is the array that I have filled up. I need to be able to find a match by the 'employer' and 'comment' and extract the value, so I can re-update this value.
Array
(
[0] => Array
(
[employer] => Albury-Wodonga
[comment] => allOtherMembers
[value] => 7
)
[1] => Array
(
[employer] => Albury-Wodonga
[comment] => associateMembers
[value] => 1
)
One command to extract and re-update the value, I suggest to use foreach loop
<?php
$arrayDif = array();
$arrayDif[] = array('employer' => "AAA", 'comment' => "comment 1", 'value' => "1");
$arrayDif[] = array('employer' => "BBB", 'comment' => "comment 2", 'value' => "2");
$arrayDif[] = array('employer' => "CCC", 'comment' => "comment 3", 'value' => "3");
// function for setting the value or returning the value
// notice the $array here is a reference to the real array
function func(&$array, $employer, $comment, $value = ''){
// $v is also a reference
foreach ($array as $k => &$v) {
if($v['employer'] == $employer && $v['comment'] == $comment) {
if(empty($value)) {
return $v['value'];
} else {
$v['value'] = $value;
}
}
}
return "Not Found.";
}
//update
func($arrayDif, 'AAA', 'comment 1', "123123");
//search
echo func($arrayDif, 'AAA', 'comment 1');
?>
Not sure if this is what you are looking for but here you go. I would use a function and simple loop.
<?php
$arrayDif = array();
$arrayDif[] = array(
array('employer' => "Albury-Wodonga", 'comment' => "allOtherMembers", 'value' => "1 star"),
array('employer' => "Employer2", 'comment' => "Good Job", 'value' => "2 stars"),
array('employer' => "Employer3", 'comment' => "Smart", 'value' => "3 stars")
);
// Function for searching the array for the matches and returning the value of the match.
function SearchMe($array, $searchEmployer, $searchComment){
for($i = 0; $i < count($array); $i++){
for($j = 0; $j < count($array[$i]); $j++){
if(
$array[$i][$j]["employer"] == $searchEmployer &&
$array[$i][$j]["comment"] == $searchComment
){
return $array[$i][$j]["value"];
}
}
}
return "No Match";
}
echo SearchMe($arrayDif, "Albury-Wodonga", "allOtherMembers");
?>

how to check whether 4 exist or not in array at 'id' key position

how to check whether 4 exist or not in array at id key position
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
),
)
The array you provided is not a valid multi-dimensional array. You need to add commas after each array in the array. Below i use array_column and in_array without using foreach
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),//add comma
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
),
);
$filtered = array_column($arr, 'id');//return the id column in this array
if(in_array(4, $filtered)){//check if 4 exists
echo '4 exists';
} else {
echo '4 does not exist';
}
?>
Quite simple, loop through the array and check if the value exists:
$value = 4;
$exists = false;
foreach($arr as $innerArr){
if($innerArr['id'] == $value){
$exists = true;
break;
}
}
If $exists is now true, the value exists within the array.
Try this one, and let me know if you face any problem.
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
foreach ($arr as $key => $value) {
if (in_array("4", $value))
{
$sub_index = $value['id'];
echo "Match found at $sub_index";
break;
}
}
Just gotta loop through your array and check existence through in_array() function.
you need something like this
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
$exists_flag = false;
foreach($arr as $inside_arr)
{
if($inside_arr['other_data'] == 4) {
$exists_flag = true;
break;
}
}
print($exists_flag);
Hope this helps!
As it stand, your array is wrong, you need to separate multi array with commas, you need to not that in_array() will not work with multi array, however you may create a recursive function that will check a provided key does exists or not in an array try code below, hope it helps ,
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
function search_items($search_value, $array)
{
foreach ($array as $item) {
if (($item == $search_value) || (is_array($item) && search_items($search_value, $item))) {
return true;
}
}
return false;
}
echo search_items("4", $arr) ? 'item found' : 'item not found';
?>
$result = array_search(4, array_column($arr, 'id'));
If we split this into steps then it would be the following:
$allColumnsNamedId = array_column($arr, 'id'); // find all columns with key 'id'
$resultBoolean = array_search(4, $allColumnsNamedId); //search the array for value 4
if($resultBoolean) {
echo 'Exists';
} else {
echo 'Does not exist';
}

build array in array in loop

This is my code! I'm trying to get from $test array and at end show me like $final array! tnx to help! code should get domain name and show how many time a userid has been repeated!
<?php
$test = array(
array(
'id' => 1,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 2,
'domain' => 'google.com',
'userid' => "456"enter
),
array(
'id' => 3,
'domain' => 'yahoo.com',
'userid' => "456"
),
array(
'id' => 4,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 5,
'domain' => 'bing.com',
'userid' => "128"
)
);
$i=0;
foreach ($test as $items) {
$domains[$i]=$items['domain'];
$userid[$i]=$items['userid'];
$i++;
}
$domain=array_unique($domains);
$domain1 = array_values($domain);
print_r($domain);
echo '<pre>';
print_r($test);
echo '</pre>';
echo '<hr>';
$d=1; $tedad = 1;
while($d<=4){
$b = 1 ; $c=0;
while ($test[$b]['id']<=4) {
if($test[$b]['domain'] == $domain1[$d])
{
$temp = $test[$b]['userid'];
if(/*$test[$b]['userid'] !==*/ !array_key_exists($domain1[$d] ['userid']){
//$domain1[$d] = array($test[$b]['userid'] => $tedad) ;
echo $temp;
$end = array(
$domain1[$d] => array(
$temp => $tedad )
);
}
else{
$end[$d][$test[$b]['userid']]= $end[$d][$test[$b]['userid']] +1;
}
}
else{
$b++;
}
}
$d++; $tedad = 1;
}
print_r($end);
$final = array(
"google.com" => array(
"123" => 2,
"456" => 1
),
"yahoo.com" => array(
"456" => 1
)
);
echo '<pre>';
print_r($final);
echo '</pre>';
echo '<hr>';
?>
Try:
$result = array();
foreach($test as $t)
{
if(isset($result[$t['domain']][$t['userid']]))
$result[$t['domain']][$t['userid']]++;
else $result[$t['domain']][$t['userid']] = 1;
}
If you don't want to include some domains use like:
$result = array();
foreach($test as $t)
{
if($t['domain'] == 'bing.com')
continue;
if(isset($result[$t['domain']][$t['userid']]))
$result[$t['domain']][$t['userid']]++;
else $result[$t['domain']][$t['userid']] = 1;
}
<?php
$test = array(
array(
'id' => 1,
'domain' => 'google.com',
'userid' => "123"
),
array(
'id' => 2,
'domain' => 'google.com',
'userid' => "456"
),
array(
'id' => 3,
'domain' => 'yahoo.com',
'userid' => "456"
),
array(
'id' => 4,
'domain' => 'google.com',
'userid' => "123"
)
);
echo '<pre>';
print_r($test);
echo '</pre>';
echo '<hr>';
$domains = array();
foreach ($test as $value) {
if (!in_array($value['domain'], $domains))
$domains[$value['domain']] = array();
}
foreach ($domains as $key => $domain) {
foreach ($test as $item) {
if ($key == $item['domain']) {
if (isset($domains[$key][$item['userid']])) {
$domains[$key][$item['userid']] = $domains[$key] [$item['userid']]+1;
} else {
$domains[$key][$item['userid']] = 1;
}
}
}
}
echo '<pre>';
print_r($domains);
echo '</pre>';
echo '<hr>';
// $final = array(
// "google.com" => array(
// "123" => 2,
// "456" => 1
// ),
// "yahoo.com" => array(
// "456" => 1
// )
// );
// echo '<pre>';
// print_r($final);
// echo '</pre>';
// echo '<hr>';
?>

Combine array elements

I want to loop through 3 arrays to create 1 single array with all 3 values in them.
See below for example and outcome.
Input:
array(
'0' => array(
'0' => array('a'),
'1' => array('b')
),
'1' => array(
'0' => array('c'),
'1' => array('d'),
'2' => array('e')
),
'2' => array(
'0' => array('f')
),
)
Outcome:
array(
'0' => 'acf',
'1' => 'adf',
'2' => 'aef',
'3' => 'bcf',
'4' => 'bdf',
'5' => 'bef'
)
Funnily I had the same problem a couple of years ago, so here's the solution I then came up with.
public static function combineElementsSuccessive($arry)
{
$result = [];
if (empty($arry) || !is_array($arry)) {
return result;
}
self::concatAndPush('', $result, $arry, 0);
return $result;
}
private static function concatAndPush($str, &$res_arry, $arry, $index)
{
foreach ($arry[$index] as $key => $val) {
$mod_str = $str . $val;
if (isset($arry[$index+1])) {
self::concatAndPush($mod_str, $res_arry, $arry, $index+1);
}
else {
$res_arry[] = $mod_str;
}
}
}
See it in action
Nevermind the static methods, I had to integrate them somehow in an application full of legacy code ;-)
How about this?
// $old_array = your original array
$new_array=array();
for ($i=0; $i<count($old_array[0]); $i++) {
for ($j=0; $j<count($old_array[1]); $j++) {
for ($k=0; $k<count($old_array[2]); $k++) {
$new_array[]=$old_array[0][$i].$old_array[1][$j].$old_array[2][$k];
}
}
}
var_dump($new_array);
It returns:
array(6) { [0]=> string(3) "acf" [1]=> string(3) "adf" [2]=> string(3) "aef" [3]=> string(3) "bcf" [4]=> string(3) "bdf" [5]=> string(3) "bef" }
Convert your array as following numbers array and run the code
$numbers = array(
array("a", "b"),
array("c", "d", "e"),
array("f"),
);
$f_nb = $numbers['0'];
$s_nb = $numbers['1'];
$t_nb = $numbers['2'];
$final_array = array();
for($a = 0; $a<sizeof($f_nb); $a++)
{
for($b = 0; $b<sizeof($s_nb); $b++)
{
for($c = 0; $c<sizeof($t_nb); $c++)
{
$final_array[] = $f_nb["$a"] . $s_nb["$b"] . $t_nb["$c"];
}
}
}
print_r($final_array);
Try this:
$array = array(
'0' => array(
'0' => array('a'),
'1' => array('b')
),
'1' => array(
'0' => array('c'),
'1' => array('d'),
'2' => array('e')
),
'2' => array(
'0' => array('f')
),
);
$outcome = array();
foreach ($array['0'] as $key => $value1)
{
foreach ($array['1'] as $value2)
{
foreach ($array['2'] as $value3)
{
$outcome[] = $value1[0].$value2[0].$value3[0];
}
}
}
print_r($outcome);

How retrieve specific duplicate array values with PHP

$array = array(
array(
'id' => 1,
'name' => 'John Doe',
'upline' => 0
),
array(
'id' => 2,
'name' => 'Jerry Maxwell',
'upline' => 1
),
array(
'id' => 3,
'name' => 'Roseann Solano',
'upline' => 1
),
array(
'id' => 4,
'name' => 'Joshua Doe',
'upline' => 1
),
array(
'id' => 5,
'name' => 'Ford Maxwell',
'upline' => 1
),
array(
'id' => 6,
'name' => 'Ryan Solano',
'upline' => 1
),
array(
'id' =>7,
'name' => 'John Mayer',
'upline' => 3
),
);
I want to make a function like:
function get_downline($userid,$users_array){
}
Then i want to return an array of all the user's upline key with the value as $userid. I hope anyone can help. Please please...
You could do it with a simple loop, but let's use this opportunity to demonstrate PHP 5.3 anonymous functions:
function get_downline($id, array $array) {
return array_filter($array, function ($i) use ($id) { return $i['upline'] == $id; });
}
BTW, I have no idea if this is what you want, since your question isn't very clear.
If you need do search thru yours array by $id:
foreach($array as $value)
{
$user_id = $value["id"];
$userName = $value["name"];
$some_key++;
$users_array[$user_id] = array("name" => $userName, "upline" => '1');
}
function get_downline($user_id, $users_array){
foreach($users_array as $key => $value)
{
if($key == $user_id)
{
echo $value["name"];
...do something else.....
}
}
}
or to search by 'upline':
function get_downline($search_upline, $users_array){
foreach($users_array as $key => $value)
{
$user_upline = $value["upline"];
if($user_upline == $search_upline)
{
echo $value["name"];
...do something else.....
}
}
}
Code :
function get_downline($userid,$users_array)
{
$result = array();
foreach ($users_array as $user)
{
if ($user['id']==$userid)
$result[] = $user['upline'];
}
return result;
}
?>
Example Usage :
get_downline(4,$array);

Categories