In my project i'm split an array index value based on regex
value. but when i want merge all array together the merge function doesn't merge.
Here is my code sample.
$testarray=array();
$merge_array=array();
//receive parameter is Admin|Manager,User@Test
foreach ($roles as $value) {
if(preg_match("/[@#%$|:\s,]+/",$value))
{
$testarray=preg_split("/[@#%$|:\s,]+/",$value);
}
print_r(array_merge($merge_array,$testarray));
}
The print_r show this result.
Array ( [0] => Admin [1] => Manager ) Array ( [0] => User [1] => Test )
You just merge arrays, but don't assign results to any variable, proper code is:
//receive parameter is Admin|Manager,User@Test
foreach ($roles as $value) {
if(preg_match("/[@#%$|:\s,]+/",$value))
{
$testarray=preg_split("/[@#%$|:\s,]+/",$value);
}
// here you add $testarray values to
// `$merge_array` on each iteration
$merge_array = array_merge($merge_array,$testarray);
}
// print result array after loop
print_r($merge_array);
The Laravel framework has nothing to do with your issue. You're using PHP's standard functions.
The array_merge function doesn't modify the array you provide to it but provides the resulting array as its output. So you should assign array_merge's result to $merge_array.
Please try the following code:
$testarray = array();
$merge_array = array();
//receive parameter is Admin|Manager,User@Test
foreach ($roles as $value) {
if(preg_match("/[@#%$|:\s,]+/",$value))
{
$testarray = preg_split("/[@#%$|:\s,]+/",$value);
}
$merge_array = array_merge($merge_array, $testarray);
}
print_r($merge_array);
You seem to think wrong. print_r(array_merge($merge_array,$testarray));
The above line is in "foreach" loop. In that case, to get a merged result, you should do like the followings; $merge_array = array_merge($merge_array,$testarray)
In your code, $merge_array remains empty, so you see the current result.
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.