简体   繁体   English

如何在 php 中的数组中替换特定键的值?

[英]How can I replace a specific key's value in an array in php?

I have a an array that has 3 values.我有一个包含 3 个值的数组。 After the user pushes the submit button I want it to replace the the value of a key that I specify with another value.在用户按下提交按钮后,我希望它用另一个值替换我指定的键的值。

If I have an array with the values (0 => A, 1 => B, 2 => C) , and the function is run, the resulting array should be (0 => A, 1 => X, 2 => C) , if for example the parameter for the function tells it to the replace the 2nd spot in the array with a new value.如果我有一个值为(0 => A, 1 => B, 2 => C)的数组,并且运行该函数,则结果数组应为(0 => A, 1 => X, 2 => C) ,例如,如果函数的参数告诉它用新值替换数组中的第二个点。

How can I replace a specific key's value in an array in php?如何在 php 中的数组中替换特定键的值?

If you know the key, you can do:如果您知道密钥,则可以执行以下操作:

$array[$key] = $newVal;

If you don't, you can do:如果你不这样做,你可以这样做:

$pos = array_search($valToReplace, $array);
if ($pos !== FALSE)
{
   $array[$pos] = $newVal;
}

Note that if $valToReplace is found in $array more than once, the first matching key is returned.请注意,如果在 $array 中多次找到 $valToReplace,则返回第一个匹配的键。 More about array_search .更多关于array_search

In case you want to have an inline solution you can use array_replace or array_replay_recrusive depending on which suits you best.如果您想要一个内联解决方案,您可以使用array_replacearray_replay_recrusive,具体取决于哪个最适合您。

$replaced_arr = array_replace([
        'key' => 'old_value',
        0 => 'another_untouched_value'
    ],[
        'key' => 'new_value'
    ]);

It would be best if your array is key/value pair如果您的数组是键/值对,那就最好了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM