I have an array like this. I get this from a server's response :
So sometimes the array is like this :
$array =
Array
(
[0] => Message: Thanks for all
[1] => Response: Goodbye
[2] =>
[3] => inactive
[4] => active call
[5] => active channels
[6] => Hello
[7] => Hi
[8] => yes
[9] => no
)
and sometimes it's like this :
$array =
Array
(
[0] => Message: Thanks for all
[1] => Response: Goodbye
[2] =>
[3] => SessionTV: 2019-06-24T17:29:53.925+0530
[4] => SessionTV: 2019-06-24T17:29:53.925+0530
[5] => SessionTV: 2019-06-24T17:29:53.925+0530
[6] => Event: 0
[7] => active channels
[8] => Hello
[9] => Hi
[10] =>
)
This is what I tried :
if (in_array("Event:", $array))
{
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
}
else
{
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
array_shift($minarr);
}
But this doesn't work.
Expected output in both cases is :
Array
(
[0] => Hello
[1] => Hi
[2] => yes
[3] => no
)
and
Array
(
[0] => Hello
[1] => Hi
[2] =>
)
So basically I just shift some rows from the array if it contains the string Event:
and shift some other rows if it doesn't contain the string Event:
.
How do I search for a string in an array like this?
you can use array_walk
with strpos
, the solution is based on the provided input
$res = [];
array_walk($array, function($v, $k) use (&$res){
if(strpos($v, ':') === false && strpos($v, 'active') === false && $v != ''){
$res[] = $v;
}
});
If the goal is to obtain all values after active channel
, and assuming that all values in the array is numerically indexed, then you can find the active channels
element with array_search()
. This returns the key of that element (first occurrence). Use this with array_slice()
to slice away those first elements. Add 1 to the return of array_search()
, as you want to remove that as well.
$key = array_search('active channels', $array);
$output = array_slice($array, $key + 1);
If your array is not numerically indexed, you can fetch the values by using array_values()
first, which is the same array, just numerically indexed.
$array = array_values($array);
$key = array_search('active channels', $array);
$output = array_slice($array, $key + 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.