如何让我的php数组数据保持不变?

时间:2016-05-18 09:52:39

标签: php

当我在foreach循环中查询数据时,它可以工作,但是对于循环中的每个传递都会重复。我尝试在循环外的任何其他位置var_dump它,数据不在那里。为什么我的数据不会在forEach循环之外持续存在?

    <?php


    $old_array = [10-2, 13=>"3452", 4=>"Green", 
5=>"Green", 6=>"Blue", "green"=>"green",
 "two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN", 
"ninja"=>"   Green ", ["blue" => "green", "green"=>"green", 2  => "itsGreen"] ];

$newArray = array();

function filter_Green($array) {



$find = "green";
$replace = "not green";

/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
/* found here: 

if (!is_array($array)) {
  /* Used ireplace so that searches can be case insensitive */
  return str_ireplace($find, $replace, $array);
}


foreach ($array as $key => $value) {

  $newArray[$key] = $value;
  if ($key == "green") {
    $newArray[$key] = "not green";
  }
  if ($value == "green") {
    $newArray[$value] = "not green";
  }


}

return $newArray;

}

filter_Green($old_array);

    var_dump($newArray);
?>

期望:当我运行该函数时,它应该替换&#34; green&#34;的所有实例。与&#34;不是绿色&#34;并将其保存到$newArray。我让它返回$ newArray,但即便如此,它似乎并没有匹配将值保存到newArray中,因此我为什么要做var_dump检查它是否能正常工作(它似乎不是)

结果:因为它是设置的,我得到一个空数组返回给我...如果我将var_dump($ newArray)移动到foreach循环中,但是然后复制每次传递的数据,似乎有点工作。 / p>

1 个答案:

答案 0 :(得分:1)

如果您希望var_dump $newArray在函数旁边,那么您应该在函数中将$newArray声明为global

<?php


$old_array = [10-2, 13=>"3452", 4=>"Green", 5=>"Green", 6=>"Blue", "green"=>"green", "two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN", "ninja"=>"   Green ", ["blue" => "green", "green"=>"green", 2  => "itsGreen"] ];

$newArray = array();

function filter_Green($array) {
global $newArray;


$find = "green";
$replace = "not green";

/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */

if (!is_array($array)) {
  /* Used ireplace so that searches can be case insensitive */
  return str_ireplace($find, $replace, $array);
}


foreach ($array as $key => $value) {

  $newArray[$key] = $value;
  if ($key == "green") {
    $newArray[$key] = "not green";
  }
  if ($value == "green") {
    $newArray[$value] = "not green";
  }


}

return $newArray;

}

filter_Green($old_array);
var_dump($newArray);

?>

但不是在函数中声明global,而是使用filter_Green($old_array);下的返回值,如下所示

$result = filter_Green($old_array);
var_dump($result);