Reputation: 61
I have a column profile in MySql
firstset=one;two;three|secondset=blue;yellow;red;|thirdset=width;height;|
(expample) I need to get: yellow
from secondset
to variable
What i wrote:
... MySql query etc ...
...
if ($r_select['profile'] != null)
{
$resultSelect = $r_select['profile'];
$resultArray = explode('|', $resultSelect);
So now i have:
resultArray (
[1] firstset=one;two;three
[2] secondset=blue;yellow;red;
[3] thirdset=width;height;
)
I need to find where in resultArray[]
is secondset=
then save this in variable- i want to get
$found = "secondset=blue;yellow;red;"
I know how to explode
variable but i cant find string in array[]
Upvotes: 1
Views: 560
Reputation: 1199
You can use array_filter function with custom anonymous function.
$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);
To obtain all array keys (in your case only one):
// output => Array ( [0] => 1 )
print_r(array_keys($matches));
Upvotes: 0
Reputation: 2595
Another solution without 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);
Then you can apply your explode on $resultString. If you have several results, like many string in your array with "secondset" on it, you will be able to process them in the array $result.
$result -> array(1) {
[1] =>
string(26) "secondset=blue;yellow;red;"
}
$resultString -> string(26) "secondset=blue;yellow;red;"
Upvotes: 0
Reputation: 1191
Are you looking something like this.
$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;
Upvotes: 0
Reputation: 8606
Try this:
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;
Result:
secondset=blue;yellow;red;
Upvotes: 1