php - Split array of strings on first space and make new array grouping by first word
Get the solution ↓↓↓I have the following array:
$phones = array(
[0] => Apple iPhone 4
[1] => Apple iPhone 5
[2] => Samsung Galaxy S6
)
What I'd like to do is split this array up, separating the brand from the model of phone, so in the end I can build an array that would give me this:
$phone_array = array (
'Apple' => array (
'iPhone 4', 'iPhone 5'
),
'Samsung' => array (
'Galaxy S6',
)
)
So far, I have the following unfinished code:
$brand_dictionary = "/(samsung|apple|htc|sony|nokia)/i";
foreach($phones as $p) {
if(stripos($p,$brand_dictionary)) {
pr($p);
die();
}
}
But this isn't working correctly at all.
Answer
Solution:
Try with -
$phones = array(
'Apple iPhone 4',
'Apple iPhone 5',
'Samsung Galaxy S6'
);
$new = array();
foreach($phones as $phone) {
$temp = explode(' ', $phone);
$key = array_shift($temp);
$new[$key][] = implode(' ', $temp);
}
var_dump($new);
Output
array(2) {
["Apple"]=>
array(2) {
[0]=>
string(8) "iPhone 4"
[1]=>
string(8) "iPhone 5"
}
["Samsung"]=>
array(1) {
[0]=>
string(9) "Galaxy S6"
}
}
Answer
Solution:
Could be simpler,
$phones = ['Apple iPhone 4','Apple iPhone 5','Samsung Galaxy S6'];
$final = [];
foreach($phones as $phone)
{
$brand_name = strtok($phone, " ");
$final[$brand_name][] = trim(strstr($phone, " "));
}
Dump of$final
,
array (size=2)
'Apple' =>
array (size=2)
0 => string 'iPhone 4' (length=8)
1 => string 'iPhone 5' (length=8)
'Samsung' =>
array (size=1)
0 => string 'Galaxy S6' (length=9)
Answer
Solution:
You only need to call one function while looping if you limit the space-splitting to 1 explosion. For concise syntax in the loop body, use array destructuring to push data into the grouped result array.
Code: (Demo)
$result = [];
foreach ($phones as $item) {
[$key, $result[$key][]] = explode(' ', $item, 2);
}
var_export($result);
Orarray_reduce()
if you prefer functional code styling. (Demo)
var_export(
array_reduce(
$phones,
function($result, $item) {
[
$key,
$result[$key][]
] = explode(' ', $item, 2);
return $result;
},
)
);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the process class relies on proc_open, which is not available on your php installation.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.