PHP将数组转换为关联数组

时间:2013-05-10 05:36:23

标签: php arrays

如何转换数组

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

进入像

这样的关联数组
Array
(
  [a]=> b,c
  [x]=> y,z
)

基本上想要将数组的值转换为键。

6 个答案:

答案 0 :(得分: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 )

答案 1 :(得分:1)

更快的解决方案:

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

答案 2 :(得分: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);
}

答案 3 :(得分: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);
}

答案 4 :(得分:0)

试试这个,

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

<强> DEMO

答案 5 :(得分: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