Reputation: 33
Sorry about the pretty bad title, I'm not a native speaker and wasn't sure how to phrase this.
Here is my problem:
I have a very long array with this format:
$array = array(
'key1.value1' => '1',
'key1.value2' => '0',
'key1.value3' => '1',
'key2.value1' => '0',
'key2.value2' => '0',
'key3.value1' => '1'
);
From this array, I would like to get another one with this format:
$newArray = array(
'key1' => array(
'value1' => '1',
'value2' => '0',
'value3' => '1'
),
'key2' => array(
'value1' => '0',
'value2' => '0'
),
'key3' => array(
'value1' => '1'
)
);
I have tried a few methods but really didn't find any solution that isn't extremely long, so I wondered if I could any tips/tricks to get this done easily!
Thanks a lot!
Upvotes: 1
Views: 42
Reputation: 1230
try this:
$generate = [];
foreach($array as $key=>$val ){
list($first, $second) = split('.', $key);
if(!isset($genrate[$first]){
$genrate[$first] = [];
if(!$genrate[$first][$second]){
$genrate[$first][$second]= [];
}
}
$genrate[$first][$second] = $val;
}
Expect it helps. Tks
Upvotes: 0
Reputation: 92854
Short solution using explode()
function:
$transformed = [];
foreach ($array as $k => $v) {
$pair = explode('.', $k);
$transformed[$pair[0]][$pair[1]] = $v;
}
print_r($transformed);
The output:
Array
(
[key1] => Array
(
[value1] => 1
[value2] => 0
[value3] => 1
)
[key2] => Array
(
[value1] => 0
[value2] => 0
)
[key3] => Array
(
[value1] => 1
)
)
Upvotes: 0
Reputation: 2347
$array = array(
'key1.value1' => '1',
'key1.value2' => '0',
'key1.value3' => '1',
'key2.value1' => '0',
'key2.value2' => '0',
'key3.value1' => '1'
);
$Results = array();
foreach($array as $key=>$value){
$KeyValue = explode(".",$key);
if(!isset($Results[$KeyValue[0]])){
$Results[$KeyValue[0]] = array();
}
$Results[$KeyValue[0]][end($KeyValue)] = $value;
}
print_r($Results);
Upvotes: 1