按数值偶数或奇数5将数组拆分为两个数组

时间:2014-06-07 09:43:17

标签: php mysql arrays

我想通过例如[SUBJECT_CODE] => 05

将以下数组拆分为奇数和偶数数组
Array
(
    [0] => Array
        (
            [0] => English
            [subject_name] => English
            [1] => E-I
            [subject_abr] => E-I
            [2] => 
            [ENROL_NO] => 
            [3] => 2013
            [YEAR_] => 2013
            [4] => 1
            [EXAM_CODE] => 1
            [5] => 42701
            [ROLL_NO] => 42701
            [6] => 01
            [SUBJECT_CODE] => 01          
        )

    [1] => Array
        (
            [0] => English
            [subject_name] => English
            [1] => E-II
            [subject_abr] => E-II
            [2] => 027-B/FMSGUK-2011
            [ENROL_NO] => 027-B/FMSGUK-2011
            [3] => 2013
            [YEAR_] => 2013
            [4] => 1
            [EXAM_CODE] => 1
            [5] => 42701
            [ROLL_NO] => 42701
            [6] => 02
            [SUBJECT_CODE] => 02         

        )

    [2] => Array
        (
            [0] => Urdu
            [subject_name] => Urdu
            [1] => U-I
            [subject_abr] => U-I
            [2] => 
            [ENROL_NO] => 
            [3] => 2013
            [YEAR_] => 2013
            [4] => 1
            [EXAM_CODE] => 1
            [5] => 42701
            [ROLL_NO] => 42701
            [6] => 05
            [SUBJECT_CODE] => 05

        )
)

2 个答案:

答案 0 :(得分:1)

为此,一个简单的foreach就足够了。考虑这个例子:

// $values is your original array
$new_values = array();
foreach ($values as $key => $value) {
    if($value['SUBJECT_CODE'] & 1) {
        $new_values['odd'][] = $value;
    } else {
        $new_values['even'][] = $value;
    }
}

echo '<pre>';
print_r($new_values);
echo '</pre>';

答案 1 :(得分:1)

第1步:遍历数组

$odd = array();
$even = array();
foreach ($arr as $key => $value) {
    if ($key % 2 == 0) {
        $even[] = $value;
    }
    else {
        $odd[] = $value;
    }
}
}

奇数值存储在$ odd数组中,甚至存储在$ even中。 你可以print_r($ odd)