将多维数组拆分为两个新数组

时间:2013-03-29 08:01:36

标签: php arrays

我有这个多维数组:

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] => 
        )

)

我有一组名为matches的ID:

    [matches] => Array
        (
            [0] => 1
            [1] => 2

        )

我需要将主阵列分成两部分:

$eduAdd = array()
$eduUpdate = array()

$eduAdd将包含不匹配的 fieldId's $eduUpdate将包含匹配的 fieldId's

$eduAdd看起来像这样:

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] => 
            )

    )

我试过这个,但发现in_array对多维数组不起作用:

foreach($filteredSubmittedData as $filteredUpdates){
    if(in_array($filteredUpdates['fieldId'], $matches)){
        echo "yup";
    }
}

我该怎么做?

2 个答案:

答案 0 :(得分:1)

$filteredUpdates['fieldId']本身就是一个阵列&因为in_array需要一个大海捞针它不会像你期望的那样工作。尝试将if条件更改为,

if(array_intersect($filteredUpdates['fieldId'], $matches)){

答案 1 :(得分:1)

<强>解决方案

考虑将$main作为您的主数组并将$matches作为您的匹配数组:

$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;
    }
}   

<强>解释

首先,我们需要填充$main['fieldId']内匹配的索引数组。这些是将移至$eduUpdate并且不会插入$eduAdd的索引:

$itodel = array();
foreach ($main['fieldId'] as $i => $v)
    if (isset($matches[$i]) and $matches[$i] == $v)
        $itodel[] = $i;

然后我们运行另一个foreach循环,实际上将$main数组拆分为另外两个。主要条件是if (in_array($i, $itodel)),因为如果我们正在观察应该进入$eduUpdate的索引,那么我们应该将其添加到其中,否则我们只需将其插入$eduAdd