0

我有这个多维数组:

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

)

我有一个名为 id 的数组matches

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

        )

我需要将主数组分成两个:

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

$eduAdd将包含不匹配的 fieldId$eduUpdate并将包含匹配的 fieldId

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

我怎样才能做到这一点?

4

2 回答 2

1

$filteredUpdates['fieldId']本身是一个数组,因为 in_array 需要一个干草堆,所以它不会像你期望的那样工作。尝试将您的 if 条件更改为,

if(array_intersect($filteredUpdates['fieldId'], $matches)){
于 2013-03-29T08:04:50.047 回答
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.

于 2013-03-29T08:32:23.700 回答