PHP根据特定要求替换Array值

时间:2014-09-04 21:42:37

标签: php html arrays html5 sorting

我有一个数组:

$array = ["1","0","0","1","1"]


//replace with

$newArray = ["honda","toyota","mercedes","bmw","chevy"]

// only if the original array had a value of "1".
// for example this is my final desired output:

$newArray = ["honda","0","0","bmw","chevy"]

我想以特定的顺序IF更改每个值,并且仅当数组值等于“1”时才会更改。

例如,值“honda”,“toyota”,“mercedes”,“bmw”,“chevy”应仅在值为“1”时替换数组值,否则不替换它们且它们必须在正确的位置,例如,数组中的第一个元素必须只能更改为本田,而不是更改为丰田或任何其他值。

我知道我必须遍历数组并提供if语句:

foreach($array as $val) {

    if($val == 1){

    //do something

  } else {
    return null;
  }
}

请指导我正确的方向,并描述如何按顺序替换值,以便丰田不能仅替换第一个数组值的第二个位置。

3 个答案:

答案 0 :(得分:4)

您可以这样 - 通过引用迭代数组并在值为1(字符串)时替换,并且替换数组中的值存在:

foreach($array as $key => &$current) {
    if($current === '1' && isset($replace[$key]))
        $current = $replace[$key];
}

Output:

Array
(
    [0] => honda
    [1] => 0
    [2] => 0
    [3] => bmw
    [4] => chevy
)

根据你的评论,要输出有价值的汽车的内爆列表,你可以做这样的事情 - 过滤掉所有零值并用逗号进行内爆:

echo implode(
    // delimiter
    ', ', 
    // callback - filter out anything that is "0"
    array_filter($array, function($a) {
        return $a != '0';
    })
);

答案 1 :(得分:2)

目前,我们的if询问$valtrue(或者是否存在),而数字数组的值是字符串。

试试这个:

$array = ["1","0","0","1","1"]
$newArray = ["honda","toyota","mercedes","bmw","chevy"]

foreach($array as $key => $val) {
  if($val === '1'){ // if you only want honda
    $array[$key] = $newArray[$key];
  } else {
    return null;
  }
}

答案 2 :(得分:0)

PHP代码

$array = array("1","0","0","1","1");
$newArray = array("honda","toyota","mercedes","bmw","chevy");

foreach($array as $key => $val) {
    if($val === '1')
        $array[$key] = $newArray[$key];
}

会产生你正在寻找的答案