Say I have two arrays:
$array1
Array
(
[app] => Array
(
[name] => PunchClock
[shifts] => Array
(
[maxhours] => 16
[minhours] => 4
)
[con] => Array
(
[moog] => 3
)
)
)
and $array2
Array
(
[app] => Array
(
[name] =>
)
)
I'm trying to find a way use the second array in order to get its corresponding value coming from the first array. For example, if I were to call:
$value = $array2['app']['name']
The corresponding value would be PunchClock. If I were to choose $array2['app']['shifts']
, the corresponding value would return an array containing maxhours
and minhours
. I've tried intersecting the arrays but not getting anywhere. I've running this in recursion but it's getting quite messy. I don't know what other options to use at this point. Any help would be appreciated.
function array_intersect_keys_recursive($a, $b)
{
$r = array();
foreach ($a as $k => $v)
{
if (is_array($a[$k]) && isset($b[$k]) && is_array($b[$k]))
{
$r[$k] = array_intersect_keys_recursive($a[$k], $b[$k]);
continue;
}
if (isset($a[$k]) && isset($b[$k]))
{
$r[$k] = $a[$k];
}
}
return $r;
}
$a = Array
(
'app' => Array
(
'name' => 'PunchClock',
'shifts' => Array
(
'maxhours' => 16,
'minhours' => 4
),
'con' => Array
(
'moog' => 3
)
)
);
$b = Array
(
'app' => Array
(
'name' => ''
)
);
$c = array_intersect_keys_recursive($a, $b);
print_r($c);
The above example will output:
Array
(
[app] => Array
(
[name] => PunchClock
)
)
Do you need something like this?
function find($array1, $array2){
foreach($array1 as $key => $value){
if($value == null){
return $array2[$key];
} elseif(is_array($value)){
return find($array2[$key], $value);
} else {
throw new Exception("value not found");
}
}
}
When you use it like this:
$array1 = array(
'app'=> array(
'name' => 'punchClock',
'shifts' => array(
)
)
);
$array2 = array(
'app'=> array(
'name' => null
)
);
echo find($array1,$array2);
it will print punchClock
check the following code
$array1['app']['name'] = 'Punch Clock';
$array1['app']['shift'] = array("maxhours" => "16", "minhours", "4");
$array1['app']['con'] = 'Moog';
$array2['app']['shift'] = array("maxhours" => "16", "minhours", "4");
$result=array_intersect($array2,$array1);
Array
(
[app] => Array
(
[shift] => Array
(
[maxhours] => 16
[0] => minhours
[1] => 4
)
)
)