help needed restructuring a php array
I was wondering if anyone could help me restructure a predefined php array. The output of my current array is:
Array
(
[71-ctns] => 1
开发者_JAVA百科[71-units] => 1
[308-units] => 1
[305-ctns] => 1
[306-units] => 2
)
And I would like it to look like:
Array
(
[71] => Array
(
[ctns] => 1
[units] => 1
)
[308] => Array
(
[units] => 1
)
[305] => Array
(
[ctns] => 1
)
[306] => Array
(
[units] => 2
)
)
Is this possible?
This should do it
$merged = array();
foreach($a as $k=>$v){
$t = explode('-',$k);
$id = intval($t[0]);
if(!array_key_exists($id, $merged))
$merged[$id] = array();
$merged[$id][$t[1]] = $v;
}
EDIT:
Sorry you should use explode instead of split.
Yes, but you need to loop (note: array_map can also work, but this example is more explicit):
$fin = array();
foreach( $complex as $item => $val )
{
$pieces = explode('-', $item);
$fin[$pieces[0]] = isset($fin[$pieces[0]])?:array();
$fin[$pieces[0]][$pieces[1]] = $val;
}
Find below code to restructure a predefined php array
<?php
$newArray=array();
$result = array("71-ctns"=>1,"71-units"=>1,"308-ctns"=>1,"308-units"=>1,"305-units"=>1,"306-units"=>2);
if(is_array($result) && count($result)>0) {
foreach($result as $key=>$val) {
$getKeyArray = explode("-",$key);
$newArray[$getKeyArray[0]][$getKeyArray[1]] =$val;
}
}
print"<pre>";
print_r($newArray);
?>
精彩评论