PHP 在数组中查找字符串

PHP find string in array

我在 MySql

中有专栏简介
firstset=one;two;three|secondset=blue;yellow;red;|thirdset=width;height;|

(示例)我需要得到: yellowsecondset 到变量

我写了什么:

... MySql query etc ...
...
if ($r_select['profile'] != null)
{       
    $resultSelect = $r_select['profile']; 

    $resultArray = explode('|', $resultSelect); 

所以现在我有:

resultArray (

[1] firstset=one;two;three
[2] secondset=blue;yellow;red;
[3] thirdset=width;height;

)

我需要在 resultArray[] 中找到 secondset= 的位置,然后将其保存在变量中 - 我想获得

 $found = "secondset=blue;yellow;red;"

我知道如何 explode 变量,但我无法在数组 []

中找到字符串

试试这个:

if ($r_select['profile'] != null) {

    $resultSelect = $r_select['profile']; 
    $resultArray  = explode('|', $resultSelect); 

    foreach ($resultArray as $data) {

        if (strpos($data, 'secondset') !== FALSE) {
            $found = $data;
            break;
        }
    }
}
echo $found;

结果:

secondset=blue;yellow;red;

你看起来像这样吗

$result = Array (

'1' =>'firstset=one;two;three',
'2' =>'secondset=blue;yellow;red;',
'3' =>'thirdset=width;height;'

);
foreach($result as $key=>$value){
    if(strpos($value,'yellow')){
        $secondset = $value;
        break;

    }

}

$result1 = explode('=', $secondset);
$result2 = explode(';', $result1[1]);
list($a,$b,$c) = $result2;
echo $b;

没有foreach的另一种解决方案:

$resultArray =  [
    'firstset=one;two;three',
    'secondset=blue;yellow;red;',
    'thirdset=width;height;',
];

// all the results matching secondset
$result = preg_grep('/.*secondset.*/', $resultArray);
// if you have only one result
$resultString = reset($result);

然后您可以对 $resultString 应用爆炸。如果你有多个结果,比如你的数组中有很多字符串,上面有 "secondset",你将能够在数组 $result.

中处理它们
$result -> array(1) {
  [1] =>
  string(26) "secondset=blue;yellow;red;"
}

$resultString -> string(26) "secondset=blue;yellow;red;"

您可以将 array_filter 函数与自定义匿名函数一起使用。

$resultArray  = array("firstset=one;two;three", "secondset=blue;yellow;red;", "thirdset=width;height;");  

$matches = array_filter($resultArray, function ($haystack) {
    return strpos($haystack, 'secondset=') !== false ? true : false;
});

   // output => Array ( [1] => secondset=blue;yellow;red; )
print_r($matches);

获取所有数组键(在你的例子中只有一个):

// output => Array ( [0] => 1 )
print_r(array_keys($matches));