根据某些标准交换数组中的元素

时间:2015-09-05 23:58:10

标签: php arrays

我正在尝试根据某些条件交换数组中的元素。 例如,我的数组有“块”,它们必须一起移动,例如在数组中移动+1点。

// bubble sort
foreach ($cleanCard as $key=>$value) {
    $cleanCard = handleGroupDirection('down', $value['groupID'], $cleanCard);
}

作为上面参数传递的$ cleanCard数组如下所示:

$cleanCard = array(
    '0' => array(
            'groupID' => 1,
            'value' => 'T PHONE'
        ),
    '1' => array
        (
            'groupID' => 1,
            'value' => ''
        ),
    '2' => array
        (
            'groupID' => 1,
            'value' => 'C CELL'
        ),
    '3' => null,
    '4' => array
        (
            'groupID' => 0,
            'value' => 'EMAIL'
        )
);

正如您在此数组中看到的那样,键#3处的元素为空,这意味着该组应向下移动1个点(即使是没有值的分组项...)。空键保留在数组中。

结果数组应如下所示:

Array
(
    [0] => 
    [1] => Array
        (
            [groupID] => 1
            [value] => T PHONE
        )

    [2] => Array
        (
            [groupID] => 1
            [value] => 
        )

    [3] => Array
        (
            [groupID] => 1
            [value] => C CELL
        )
    [4] => Array
        (
            [groupID] => 0
            [value] => EMAIL
        )

)

我的代码如下:

function handleGroupDirection($direction, $groupID, $card) {
    $groupArr = array_map(function($field) { return $field['groupID']; }, $card);
    $groupKeys = array_keys($groupArr, $groupID);
    $firstFieldOfGroupIndex = $groupKeys[0];
    $lastFieldOfGroupIndex = end($groupKeys);

    switch ($direction) {
        case 'down':
            if ($lastFieldOfGroupIndex+1 >= count($card)) break;

            if ($card[$lastFieldOfGroupIndex+1] == null) {
                // move each field of the group down, starting
                // from the last field in the group

                for ($i = count($groupKeys); $i >= 0; $i--) {
                    $currentCardIndex = $groupKeys[$i];
                    $card[$currentCardIndex+1] = $card[$currentCardIndex];
                }

                // make the first field of the group null, the null spot we took is now basically going in front of the group
                $card[$firstFieldOfGroupIndex] = null;

            }

            break;
    }

    return $card;
}

尚未成功使用此代码。

编辑: 我收到通知:

NOTICE Undefined offset: 3 on line number 20
$currentCardIndex = $groupKeys[$i];
NOTICE Undefined index: on line number 21
$card[$currentCardIndex+1] = $card[$currentCardIndex];

我得到的当前数组是:

Array
(
    [0] => 
    [1] => Array
        (
            [groupID] => 1
            [value] => T PHONE
        )

    [2] => 
    [3] => Array
        (
            [groupID] => 1
            [value] => C CELL
        )

    [4] => Array
        (
            [groupID] => 0
            [value] => EMAIL
        )

)

[2]不应该是空的!

0 个答案:

没有答案