将未指定的数组值替换为 0

发布于 2024-10-19 23:40:48 字数 335 浏览 2 评论 0 原文

我想将除 workhome 之外的所有数组值替换为 0。

输入:

$array = ['work', 'homework', 'home', 'sky', 'door']

我的编码尝试:

$a = str_replace("work", "0", $array);

预期输出:

['work', 0, 'home', 0, 0]

另外,我的输入数据来自用户提交,并且数组元素的数量可能非常大。

I want to replace all array values with 0 except work and home.

Input:

$array = ['work', 'homework', 'home', 'sky', 'door']

My coding attempt:

$a = str_replace("work", "0", $array);

Expected output:

['work', 0, 'home', 0, 0]

Also my input data is coming from a user submission and the amount of array elements may be very large.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

梦里°也失望 2024-10-26 23:40:48

更优雅、更短的解决方案。

$aArray = array('work','home','sky','door');   

foreach($aArray as &$sValue)
{
     if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}

的&运算符是指向数组中特定原始字符串的指针。 (而不是该字符串的副本)
您可以通过这种方式为数组中的字符串分配一个新值。您唯一不能做的事情是任何可能扰乱数组顺序的事情,例如 unset() 或键操作。

上面示例的结果数组将是

$aArray = array('work','home', 0, 0)

A bit more elegant and shorter solution.

$aArray = array('work','home','sky','door');   

foreach($aArray as &$sValue)
{
     if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}

The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.

The resulting array of the example above will be

$aArray = array('work','home', 0, 0)
伊面 2024-10-26 23:40:48

循环将多次执行一系列操作。因此,对于数组中的每个元素,您将检查它是否等于您要更改的元素,如果是,请更改它。另外,请务必在字符串周围加上引号

//Setup the array of string
$asting = array('work','home','sky','door')

/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
   //Check if the value at the 'ith' element in the array is the one you want to change
  //if it is, set the ith element to 0
    if ($asting[$i] == 'work' || $asting[$i] == 'home')
       $asting[$i] = 0;
}

以下是一些建议阅读:

http://www.php.net/manual/en/language.types.array.php。 php.net/manual/en/language.types.array.php

http:// /www.php.net/manual/en/language.control-structs.php

但是,如果您在循环等方面遇到困难,您可能需要阅读一些介绍性编程材料。这应该可以帮助您真正了解正在发生的事情。

A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings

//Setup the array of string
$asting = array('work','home','sky','door')

/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
   //Check if the value at the 'ith' element in the array is the one you want to change
  //if it is, set the ith element to 0
    if ($asting[$i] == 'work' || $asting[$i] == 'home')
       $asting[$i] = 0;
}

Here is some suggested reading:

http://www.php.net/manual/en/language.types.array.php

http://www.php.net/manual/en/language.control-structures.php

But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.

谁的新欢旧爱 2024-10-26 23:40:48

另一种更快的方法,但确实需要一个循环:

//Setup the array of string
    $asting = array('bar', 'market', 'work', 'home', 'sky', 'door');

//Setup the array of replacings
    $replace = array('home', 'work');

//Loop them through str_replace() replacing with 0 or any other value...
    foreach ($replace as $val) $asting = str_replace($val, 0, $asting);

//See what results brings:    
    print_r ($asting);

将输出:

Array
(
    [0] => bar
    [1] => market
    [2] => 0
    [3] => 0
    [4] => sky
    [5] => door
)

A bit other and much quicker way, but true, need a loop:

//Setup the array of string
    $asting = array('bar', 'market', 'work', 'home', 'sky', 'door');

//Setup the array of replacings
    $replace = array('home', 'work');

//Loop them through str_replace() replacing with 0 or any other value...
    foreach ($replace as $val) $asting = str_replace($val, 0, $asting);

//See what results brings:    
    print_r ($asting);

Will output:

Array
(
    [0] => bar
    [1] => market
    [2] => 0
    [3] => 0
    [4] => sky
    [5] => door
)
从﹋此江山别 2024-10-26 23:40:48

使用 array_map 的替代方案:

$original = array('work','home','sky','door');

$mapped = array_map(function($i){
    $exclude = array('work','home');
    return in_array($i, $exclude) ? 0 : $i; 
}, $original);

An alternative using array_map:

$original = array('work','home','sky','door');

$mapped = array_map(function($i){
    $exclude = array('work','home');
    return in_array($i, $exclude) ? 0 : $i; 
}, $original);
傲性难收 2024-10-26 23:40:48

你可以尝试 array_walk 函数:

function zeros(&$value) 
{ 
    if ($value != 'home' && $value != 'work'){$value = 0;}      
}   

 $asting = array('work','home','sky','door','march');   

 array_walk($asting, 'zeros');
 print_r($asting);

you may try array_walk function:

function zeros(&$value) 
{ 
    if ($value != 'home' && $value != 'work'){$value = 0;}      
}   

 $asting = array('work','home','sky','door','march');   

 array_walk($asting, 'zeros');
 print_r($asting);
枫林﹌晚霞¤ 2024-10-26 23:40:48

您还可以将数组作为 str_replace 上的参数 1 和 2...

You can also give array as a parameter 1 and 2 on str_replace...

旧人 2024-10-26 23:40:48

只是 for 循环的一个小要点。许多人没有意识到第二个比较任务是在每次新的迭代中完成的。因此,如果是大数组或计算的情况,您可以通过执行以下操作来优化循环:

for ($i = 0, $c = count($asting); $i < $c; $i++) {...}

您可能还想查看 http://php.net/manual/en/function.array-replace.php 对于原始问题,除非代码确实是最终的:)

Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:

for ($i = 0, $c = count($asting); $i < $c; $i++) {...}

You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)

乙白 2024-10-26 23:40:48

试试这个

$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
     $key = array_search($val, $your_array);
     $your_array[$key] = 0;
}
print_r($your_array);

Try This

$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
     $key = array_search($val, $your_array);
     $your_array[$key] = 0;
}
print_r($your_array);
羞稚 2024-10-26 23:40:48

本页上有一些技术可以实现零迭代函数调用——这在性能方面非常好。为了获得最佳的可维护性,我建议将目标字符串列表分隔为查找数组。通过引用修改原始数组值,您可以快速替换整个字符串并将非目标值 null 合并为 0。

代码:(演示

$array = ['work', 'homework', 'home', 'sky', 'door'];

$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);

foreach ($array as &$v) {
    $v = $lookup[$v] ?? 0;
}

var_export($array);

输出:

array (
  0 => 'work',
  1 => 0,
  2 => 'home',
  3 => 0,
  4 => 0,
)

您只需扩展 $keep 即可非常轻松、干净地扩展目标字符串列表。


如果您不想要经典循环,则可以使用相同的技术而无需修改原始数组。 (演示

var_export(
    array_map(fn($v) => $lookup[$v] ?? 0, $array)
);

There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.

Code: (Demo)

$array = ['work', 'homework', 'home', 'sky', 'door'];

$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);

foreach ($array as &$v) {
    $v = $lookup[$v] ?? 0;
}

var_export($array);

Output:

array (
  0 => 'work',
  1 => 0,
  2 => 'home',
  3 => 0,
  4 => 0,
)

You can very easily, cleanly extend your list of targeted strings by merely extending $keep.


If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)

var_export(
    array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
世界如花海般美丽 2024-10-26 23:40:48

这是我的最终代码

//Setup the array of string
$asting = array('work','home','sky','door','march');

/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
   $asting[$i] = 20;
} elseif($asting[$i] == 'home'){
    $asting[$i] = 30;

}else{
    $asting[$i] = 0;
}

echo $asting[$i]."<br><br>";

$total += $asting[$i];
}

echo $total;

this my final code

//Setup the array of string
$asting = array('work','home','sky','door','march');

/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
   $asting[$i] = 20;
} elseif($asting[$i] == 'home'){
    $asting[$i] = 30;

}else{
    $asting[$i] = 0;
}

echo $asting[$i]."<br><br>";

$total += $asting[$i];
}

echo $total;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文