如何轉換數組PHP轉換陣列關聯數組
Array
(
[1] => a,b,c
[2] => x,y,z
)
到一個關聯數組一樣
Array
(
[a]=> b,c
[x]=> y,z
)
基本上要一個數組的值轉換成鍵。
如何轉換數組PHP轉換陣列關聯數組
Array
(
[1] => a,b,c
[2] => x,y,z
)
到一個關聯數組一樣
Array
(
[a]=> b,c
[x]=> y,z
)
基本上要一個數組的值轉換成鍵。
試試這個,
$newArray = array();
foreach($array as $data){
$values = explode(",",$data);
$key = array_shift($values);
$newArray[$key] = implode($values,",");
}
print_r($newArray);
DEMO。
嘗試像
$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);
}
我的工作不正常.. ?? – Gautam3164 2013-05-10 05:59:09
這樣做:
$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);
}
如何:
$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)
試試這個
<?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);
?>
一個更快的解決方案:
foreach($array as $item){
$x = explode(',',$item);
$new_array[$x[0]] = implode(','array($x[1],$x[2]));
}
print_r($new_array);
你想擁有的第一個值,在'A,B,C''了',轉換爲其餘的關鍵? – SAVAFA 2013-05-10 05:37:51
@SaVaFa是的,我想要有第一個值作爲關鍵 – blakcaps 2013-05-10 05:39:16