2013-05-10 110 views
0

如何轉換數組PHP轉換陣列關聯數組

Array 
(
    [1] => a,b,c 
    [2] => x,y,z 
) 

到一個關聯數組一樣

Array 
(
    [a]=> b,c 
    [x]=> y,z 
) 

基本上要一個數組的值轉換成鍵。

+0

你想擁有的第一個值,在'A,B,C''了',轉換爲其餘的關鍵? – SAVAFA 2013-05-10 05:37:51

+0

@SaVaFa是的,我想要有第一個值作爲關鍵 – blakcaps 2013-05-10 05:39:16

回答

0

試試這個,

$newArray = array(); 
foreach($array as $data){ 
    $values = explode(",",$data); 
    $key = array_shift($values); 
    $newArray[$key] = implode($values,","); 
} 
print_r($newArray); 

DEMO

0

嘗試像

$res = array(); 
foreach($my_arr as $value) 
{ 
    $my_var[] = explode(',',$value); 
    $i = 0; 
    foreach($my_var as $ky) 
    { 
     if($i++ != 0) 
     $exp_arr[] = $ky; 
    } 
    $res[$my_var[0]] = implode(',',$exp_arr); 
} 

,或者你可以不設置像

foreach($my_arr as $value) 
{ 
    $my_var[] = explode(',',$value); 
    $temp = $my_var[0]; 
    unset($my_var[0]); 
    $res[$temp] = implode(',',$my_var); 
} 
+0

我的工作不正常.. ?? – Gautam3164 2013-05-10 05:59:09

0

這樣做:

$myArray=array(1=>'a,b,c', 2=>x,y,z); 
foreach($myArray as $val){ 
    $Xval=explode(",",$val); 
    $newKey=$Xval[0]; 
    unset($Xval[0]); 
    $newArray[$newKey]=implode(",",$Xval); 
} 
1

如何:

$arr = array('a,b,c','x,y,z'); 

$newArr = array(); 


foreach($arr as $key => $value) { 

    $value = explode(",",$value); 
    $firstValue = $value[0]; 
    array_shift($value); 
    $newArr[$firstValue] = implode(",",$value); 

} 

print_r($newArr); //Array ([a] => b,c [x] => y,z) 
0

試試這個

<?php 
$array=array('a,b,c', 'x,y,z'); 
foreach($array as $key=>$val) 
{ 
    $array[substr($val,0,1)]=substr($val,2); 
    unset($array[$key]); 
} 

print_r($array); 
?> 

See Demo

1

一個更快的解決方案:

foreach($array as $item){ 
    $x = explode(',',$item); 
    $new_array[$x[0]] = implode(','array($x[1],$x[2])); 
} 
print_r($new_array);