PHP:将数组与字符串(或数组)进行比较并添加到该字符串? [英] PHP: Compare an array against a string (or an array) and add to that string?

查看:50
本文介绍了PHP:将数组与字符串(或数组)进行比较并添加到该字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 php 还很陌生,所以我不确定它的名称和术语我想在这里了解一下.我确实在 SE 上进行了搜索,但尽管问题的标题是相似的,他们问的是完全不同的不幸的是,甚至没有部分相关的东西.对不起如果存在而我找不到,请提前.

I am fairly new to php so I am not sure of the names and terms of what I would like to find out here. I did do a search on SE but although the titles of questions are similar, they ask a completely different thing which are unfortunately not partially related even. Excuse me in advance if it exists and I could not find.

我有一个字符串 $str='somevalue'; 或一个 $array = ['s', 'o', 'm' ..];

I have a string $str= 'somevalue'; or an $array = ['s', 'o', 'm' ..];

现在,我有另一个二维数组,其中第 1 个项目我想根据这个主数组检查,并根据它们是否存在,添加第二个项目.

Now, I have an other array which is 2 dimensional, of which 1st items I want to check against this main array and depending on whether they exist or not, add the 2nd item.

$to_match[] = ('match' => 'rnd_letter', 'if_not_add' => 'someval');
$to_match[] = ('match' => 'rnd_letter', 'if_not_add' => 'someval_x');
..

rnd_letter 是一个字母或字母组合,someval 是一样的.

rnd_letter is a letter or combination of letters and someval is the same.

如何检查 $str 中是否存在 'match' 中的字母,如果不存在,则添加到数组的 'if_not_add' 末尾字母?

How can I check if letter(s) in 'match' exists in $str, and if not, add to the end letters of 'if_not_add' of the array?

非常感谢.

推荐答案

$to_match = array();
$to_match[] = array('match' => 'hello', 'if_not_add' => 'value 1');
$to_match[] = array('match' => 'abc', 'if_not_add' => 'value 2');
$to_match[] = array('match' => 'w', 'if_not_add' => 'value 3');

$str = 'Hello World!';
$new_array = array();

foreach($to_match as $value) {
  if(!stristr($str, $value['match'])) {
    $new_array[] = $value['if_not_add'];
  }
}

var_dump($new_array); // outputs array(1) { [0]=> string(7) "value 2" } 

这将遍历每个数组元素,然后检查 match 的值是否存在于 $str 中,如果不存在,则将其添加到 $new_array(我想这就是你要找的?)

This will iterate over each array element, then check if the value of match exists in $str, if not it will add it to $new_array (I think that's what you were looking for?)

这篇关于PHP:将数组与字符串(或数组)进行比较并添加到该字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆