PHP在数组中查找字符串
我在MySql中有一个列配置文件PHP在数组中查找字符串,php,explode,Php,Explode,我在MySql中有一个列配置文件 firstset=one;two;three|secondset=blue;yellow;red;|thirdset=width;height;| (expample)我需要获取:黄色从第二集到变量 我写的是: ... MySql query etc ... ... if ($r_select['profile'] != null) { $resultSelect = $r_select['profile']; $result
firstset=one;two;three|secondset=blue;yellow;red;|thirdset=width;height;|
(expample)我需要获取:黄色
从第二集
到变量
我写的是:
... 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;"
我知道如何分解变量,但在数组[]中找不到字符串
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;"
您可以将函数与自定义匿名函数一起使用
$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);
要获取所有数组密钥(在您的情况下,仅获取一个):
_array()中的
不符合您在数组中查找字符串的要求吗?如果您规范化了数据库,而不是将所有内容存储在一列中,事情会变得容易得多。他的两个注释都是正确的,可以通过$resultArray
进行循环。首先在=
上拆分元素,然后在上拆分元素的第二部分代码>。然后在数组()中使用
搜索该数组中的“yellow”
.Barmar-首先:我只能用profie在数据库中创建新表,但大约有40个kolumns。还可以吗?只是问问而已。第二:但是如果黄色
也将在第一集
中?那么什么会更好呢?创建新表或摆弄它?因为break
你不认为下一个索引是否也有将被忽略的yellow
?@kafus如果你的数组有多个相同的值,那么只有第一个会出现,其他的会跳过。检查一下。例如:-resultArray([1]第一集=1;二;三[2]第二集=blue;黄色;红色;[3]第三集=width;height;[4]第三集=width;height;yellow;)
是的,但首先我将使用secondset=blue;黄色的;红色代码>然后我可以查找我的“黄色”
。没有选项可以获得2xsecondset
// output => Array ( [0] => 1 )
print_r(array_keys($matches));