0

如何转换数组

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

成一个关联数组,如

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

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

4

6 回答 6

1

更快的解决方案:

foreach($array as $item){
    $x = explode(',',$item);
    $new_array[$x[0]] = implode(','array($x[1],$x[2]));
}
print_r($new_array);
于 2013-05-10T06:06:48.870 回答
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 )
于 2013-05-10T05:47:15.953 回答
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);
}
于 2013-05-10T05:43:44.840 回答
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);
}
于 2013-05-10T05:44:44.797 回答
0

试试这个,

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

演示

于 2013-05-10T05:47:25.073 回答
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);
?>

看演示

于 2013-05-10T05:50:56.857 回答