簡體   English   中英

將值附加到多維數組PHP

[英]Append value to multidimensional array 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;
}

您需要在兩個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;
}

只需改變這一行

$append .= $parameter;

對此

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

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

更多方法,以實現相同的結果,例如使用array_map()

[akshay@localhost 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 )
);


?>

輸出:

[akshay@localhost 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
        )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM