0

How do I convert the array

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

into an associative array like

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

Basically want to convert value of an array into a key.

2
  • Do you want to have the first value, a in a,b,c, converted to the key for the rest? Commented May 10, 2013 at 5:37
  • @SaVaFa Yes, I want to have first value as key Commented May 10, 2013 at 5:39

6 Answers 6

1

How about this:

$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 )
Sign up to request clarification or add additional context in comments.

Comments

1

A faster solution:

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

Comments

0

Try out this,

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

DEMO.

Comments

0

Do this:

$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);
}

Comments

0

Try like

$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);
}

or you can unset like

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

Comments

0

try this

<?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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.