2016-02-05 128 views
0

我要么通过疲劳障碍工作,要么我对PHP的理解存在严重的空白。以下是我需要做对嵌套数组元素的修改不会停留

  • 我有数组的数组()(一个
  • 我需要通过为每个所述内阵列的外部阵列和
  • 迭代我需要添加一个新元素,而这个元素又是一个数组
  • 这是我每天多次出现的代码,并且我预料到它没有什么问题。然而,出乎我的意料,而我可以修改一个我不能让这些修改棍子出现在一个

下面是代码

function fillRouteNames($routes,$export) 
{ 
for($i=0;$i < count($routes);$i++) 
{ 
    $route = $routes[$i]; 
    trigger_error(gettype($route));//shows Array, as expected 
    $disps = $route['d']; 
    $nd = array(); 
    foreach($disps as $disp) $nd[] = fxnName($disp,$export); 
    //now I have the new element I want to add 
$route['nd'] = $nd; 
trigger_error(json_encode($route)); 
/as expected the output shows the new element, nd 
} 
trigger_error(json_encode($routes)); 
//but now it is gone - it is like I never did $oute['nd'] = $nd 

}

必须有这里有一些非常明显的错误,但我一直无法弄清楚。我希望这里的某个人能够发现这个问题。

回答

1

PHP数组按值分配,而不是引用。这意味着修改副本时,更改不会影响原件。 $route$routes[$i]是不同的阵列。

一种可能的解决办法是复制$route回来了$routes[$i]你更新后:

for ($i = 0; $i < count($routes); $i ++) { 
    // Copy $routes[$i] into $routes for quick access and shorter code 
    $route = $routes[$i]; 

    // Update $route as needed 
    $route['nd'] = $nd; 
    // ... more updates ... 

    // Copy $route back over $routes[$i] 
    $routes[$i] = $route; 
} 
+0

谢谢!问题的完美总结!虽然我担心它不能提供一个解决方案。 – DroidOS

+0

增加了一个可能的解决方案。还有其他的解决方案:使用[本答案](http://stackoverflow.com/a/35229858/4265352)中描述的引用(引用可以使代码以更意想不到的方式破解),将'$ (更新与否)到一个新的数组(并在循环后放弃原始数组),使用对象而不是数组等。 – axiac

2

那是因为$route是内部数组的一个副本。您需要添加参考或使用直接索引$routes[$i]。就像这样:

function fillRouteNames($routes,$export) 
{ 
    for($i=0;$i < count($routes);$i++) 
    { 
     $route = &$routes[$i];// add a reference 

     trigger_error(gettype($route)); 

     $disps = $route['d']; 
     $nd = array(); 
     foreach($disps as $disp) $nd[] = fxnName($disp,$export); 

     $routes[$i]['nd'] = $nd;// OR use an index 

     trigger_error(json_encode($route)); 
    } 
    trigger_error(json_encode($routes)); 
} 
-1

不应该最后一行是trigger_error(json_encode($ route));

0

以下是我最后做

function fillRouteNames($routes,$export) 
{ 
for($i=0;$i < count($routes);$i++) 
{ 
    $disps = $routes[$i]['d']; 
    $nd = array(); 
    foreach($disps as $disp) $nd[] = fxnName($disp,$export); 
    $routes[$i]['nd'] = $nd; 
} 
return $routes; 
} 

这只是避免造成规避该问题的嵌套数组元素的本地副本。