I am new to PHP an needed little help. It may be easy for some but giving me a tough time.
I have an array
Array ( [0] => page-18 [1] => page-20 )
Which I would like to explode further by '-':
$mainStringBrk = array('page-18', 'page-20');
$finalArray = array();
foreach($mainStringBrk as $bString){
$mainStringBrkBrk = explode('-', $bString);
$finalArray[$mainStringBrkBrk[0]] = $mainStringBrkBrk[1];
}
echo '<pre>'; print_r($finalArray);
When I do, it outputs only the last key and value of array.
Array ( page => 20 )
My desired output is:
Array ( page => 18, page => 20 )
I am wondering if anyone can guide me in right direction.
You can't achieve the result you want as it is not possible to have an array with identical keys; this is why you only have one result in your output. You could change your output structure to a 2-dimensional array to work around this eg
$mainStringBrk = array('page-18', 'page-20');
$finalArray = array();
foreach($mainStringBrk as $bString){
$mainStringBrkBrk = explode('-', $bString);
$finalArray[$mainStringBrkBrk[0]][] = $mainStringBrkBrk[1];
}
print_r($finalArray);
Output:
Array
(
[page] => Array
(
[0] => 18
[1] => 20
)
)
Or you can adopt this structure if it is better suited to your needs:
$finalArray = array();
foreach($mainStringBrk as $bString){
$mainStringBrkBrk = explode('-', $bString);
$finalArray[] = array($mainStringBrkBrk[0] => $mainStringBrkBrk[1]);
}
print_r($finalArray);
Output:
Array
(
[0] => Array
(
[page] => 18
)
[1] => Array
(
[page] => 20
)
)
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.