2017-09-26 103 views
2

我在PHP多維數組顯示爲:追加值到多維數組PHP

Array 
(
    [0] => Array 
    (
     [background] => https://example.com/image.jpg 
     [description] => Example text 
     [url] => https://example.com 
    ) 

    [1] => Array 
    (
     [background] => https://example.com/image.jpg 
     [description] => Example text 
     [url] => https://example.com 
    ) 
) 

我想通過這個數組循環和相同的參數附加到兩個url密鑰。我試着通過一個帶有雙foreach循環的函數來做到這一點,並且能夠成功追加參數,但是我無法返回具有更新值的數組。

這裏是我試過:

呼叫

$array = append_field($array, 'url', '?parameter=test'); 

功能

function append_field($array, $field, $parameter) 
{ 
    foreach ($array as $inner_array) : 
     foreach ($inner_array as $key => $append) : 
      if ($key == $field) : 
       $append .= $parameter; 
      endif; 
     endforeach; 
    endforeach; 

    return $array; 
} 

回答

3

你需要傳遞數組值均參考的foreach循環來能夠寫信給他們。否則,你正在迭代你的值的副本。

編號:http://php.net/manual/en/language.references.php

function append_field($array, $field, $parameter) 
{ 
    foreach ($array as &$inner_array) : 
     foreach ($inner_array as $key => &$append) : 
      if ($key == $field) : 
       $append .= $parameter; 
      endif; 
     endforeach; 
    endforeach; 

    return $array; 
} 

但你也可以通過寫全陣列路徑包括這兩個鍵做沒有引用,這個時候:

function append_field($array, $field, $parameter) 
{ 
    foreach ($array as $i => $inner_array) : 
     foreach ($inner_array as $key => $append) : 
      if ($key == $field) : 
       $array[$i][$key] .= $parameter; 
      endif; 
     endforeach; 
    endforeach; 

    return $array; 
} 
3

只是改變這一行

$append .= $parameter; 

to this

$inner_array[$key] = $append.$parameter 

foreach ($array as $inner_array):foreach ($array as &$inner_array) :

2

一些更多的方式,使用相同的實現結果,例如array_map()

[[email protected] tmp]$ cat test.php 
<?php 
$arr = array(
    array(
     'background'=>'https://example.com/image.jpg', 
     'description'=>'Example text', 
     'url'=>'https://example.com' 
    ), 
    array(
     'background'=>'https://example.com/image.jpg', 
     'description'=>'Example text', 
     'url'=>'https://example.com' 
    ), 

); 

$append = array('url'=>'?parameter=test'); 
print_r( 
    array_map(function($item) use ($append) {foreach($append as $k => $v){ if(isset($item[$k]))$item[$k].=$v;}return $item;}, $arr) 
); 


?> 

輸出:

[[email protected] tmp]$ php test.php 
Array 
(
    [0] => Array 
     (
      [background] => https://example.com/image.jpg 
      [description] => Example text 
      [url] => https://example.com?parameter=test 
     ) 

    [1] => Array 
     (
      [background] => https://example.com/image.jpg 
      [description] => Example text 
      [url] => https://example.com?parameter=test 
     ) 

)