简体   繁体   English

如果数组包含特定字符,则返回所有字符串php

[英]If array contains a specific character, return all of the string php

Let's say I have a php array like this: 假设我有一个像这样的php数组:

$compare  = array("Testing", "Bar");
$my_array = array(
                "Foo=7654", "Bar=4.4829", "Testing=123" 
        );

So it's safe to say below: 因此,可以肯定地说:

$compare[0] = "Testing"  

So I wanna check if $my_array contains $compare[0] (in above case, yes it does) And if it contains returns that value from $my_array which is Testing=123 所以我想检查$my_array包含$compare[0] (在上面的情况下,是的),并且如果包含$my_array值返回Testing = 123的值。

How's that possible? 那怎么可能

You may use foreach loop: 您可以使用foreach循环:

$result = array();
foreach ($compare as $comp) {
    foreach ($my_array as $my) {
        if (strpos($my, $comp) !== false) {
            $result[] = $comp;
        }
    }
}

in array $result is result of search 数组$result是搜索的结果

or by other way: 或通过其他方式:

$result = array();
foreach ($compare as $comp) {
    foreach ($my_array as $my) {
        if ($comp = explode('=', $my)[0]) {
            $result[] = $comp;
        }
    }
}

To use a single loop... 要使用单个循环...

$compare  = array("Testing", "Bar");
$my_array = array(
    "Foo=7654", "Bar=4.4829", "Testing=123"
);
$output = [];

foreach ( $my_array as $element )   {
    if ( in_array(explode('=', $element)[0], $compare)){
        $output[] = $element;
    }
}
print_r($output);

This just checks that the first part of the value (before the =) is in the $compare array. 这只是检查值的第一部分(在=之前)是否在$compare数组中。

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

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