I have this multidimensional array:
Array
(
[userId] => 35
[fieldId] => Array
(
[0] => 1
[1] => 2
[2] => 3
[4] => 4
)
[educationTitle] => Array
(
[0] => School1
[1] => School2
[2] => 3
[4] =>
)
[educationDegree] => Array
(
[0] => Degree1
[1] => Degree2
[2] => 3
[4] =>
)
[startDate] => Array
(
[0] => 2013-03-01
[1] => 2013-03-03
[2] => 1970-01-01
)
[endDate] => Array
(
[0] => 2013-03-02
[1] => 2013-03-04
[2] => 1970-01-01
)
[educationDescription] => Array
(
[0] => Description1
[1] => Description2
[2] =>
)
)
And I have an array of ids called matches
:
[matches] => Array
(
[0] => 1
[1] => 2
)
I need to split the main array into two:
$eduAdd = array()
$eduUpdate = array()
$eduAdd
will contain the non-matching fieldId's and $eduUpdate
will contain the matching fieldId's.
$eduAdd
Would look like this:
Array
(
[userId] => 35
[fieldId] => Array
(
[2] => 3
[4] => 4
)
[educationTitle] => Array
(
[2] => 3
[4] =>
)
[educationDegree] => Array
(
[2] => 3
[4] =>
)
[startDate] => Array
(
[2] => 1970-01-01
)
[endDate] => Array
(
[2] => 1970-01-01
)
[educationDescription] => Array
(
[2] =>
)
)
I tried this, but found out in_array
does not work on multidimensional arrays:
foreach($filteredSubmittedData as $filteredUpdates){
if(in_array($filteredUpdates['fieldId'], $matches)){
echo "yup";
}
}
How can I do this?
Solution
Considering $main
to be your main array and $matches
to be your matches array:
$eduAdd = array();
$eduUpdate = array();
$itodel = array();
foreach ($main['fieldId'] as $i => $v)
if (isset($matches[$i]) and $matches[$i] == $v)
$itodel[] = $i;
foreach ($main as $key => $arr) {
if (!is_array($arr)) continue;
foreach ($arr as $i => $v) {
if (in_array($i, $itodel))
$eduUpdate[$key][$i] = $v;
else
$eduAdd[$key][$i] = $v;
}
}
Explanation
First of all we need to populate an array of indexes that are matched inside $main['fieldId']
. Those are the indexes that will be moved to $eduUpdate
and that will not be inserted into $eduAdd
:
$itodel = array();
foreach ($main['fieldId'] as $i => $v)
if (isset($matches[$i]) and $matches[$i] == $v)
$itodel[] = $i;
Then we run another foreach
loop that will actually split the $main
array into the other two. The main condition is if (in_array($i, $itodel))
because if we are watching an index that is inside the ones that should go into $eduUpdate
then we should add it to it, otherwise we just insert it into $eduAdd
.
$filteredUpdates['fieldId']
itself is an array & as in_array needs a haystack it won't work as you expect. Try changing your if condition as,
if(array_intersect($filteredUpdates['fieldId'], $matches)){