如何在PHP中替换数组值

时间:2012-01-22 12:50:23

标签: php

我需要替换下面的数组“[4] => 1”第4个基于值的条件。 1 => “你好”或0 =>“海”

Array (
[0] => Array ( [0] => 33 [1] => Test [2] => test2@gmail.com [3] => [4] => 1 )
[1] => Array ( [0] => 36 [1] => Test2 [2] => test3@gmail.com [3] => [4] => 0 )
[2] => Array ( [0] => 37 [1] => Test4 [2] => test4@gmail.com [3] => [4] => 0 )
[3] => Array ( [0] => 38 [1] => Test5 [2] => test5@gmail.com [3] => [4] => 0 )
)

请告诉我如何用PHP进行操作。

3 个答案:

答案 0 :(得分:2)

你走了:

for($i=0;$i<count($array);$i++)
{
        $array[$i][4] = ($array[$i][4] == 1);
}

这会将1替换为true,将其他任何内容替换为false

答案 1 :(得分:1)

将它投射到布尔会做到这一点。对于单个元素(在这种情况下为0):

$arr[0][4] = (bool)$arr[0][4];

对于所有元素,请使用array_map或循环:

foreach($array as $value) {
    $value[4] = (bool)$value[4];
}

答案 2 :(得分:0)

foreach($array as $subArray){

    switch ($subArray[4]){
        case 1:
            $subArray[4] = "Hello";
            break;
        case 0:
            $subArray[4] = "Hai";
            break;
    }
}