+ -
当前位置:首页 → 问答吧 → php 索引数据转化为对象数组方法 求高手

php 索引数据转化为对象数组方法 求高手

时间:2011-11-29

来源:互联网

把这样的索引数组转化为对象 并且对象为 每个desi_id的值
PHP code
Array ( [0] => Array ( [desi_id] => 1 [desi_name] => 黑色 [desi_price] => 0 [desi_type] => 1 [desi_content] => 黑色黑色黑色 [desi_pnum] => 001 [tid] => 1 [image] => http://cphz.hichina.com/images/base_mg02.gif ) [1] => Array ( [desi_id] => 2 [desi_name] => 红色 [desi_price] => 200 [desi_type] => 1 [desi_content] => 红色烤漆 [desi_pnum] => 002 [tid] => 1 [image] => http://cphz.hichina.com/images/150x60.jpg ) [2] => Array ( [desi_id] => 3 [desi_name] => 红色 [desi_price] => 200 [desi_type] => 1 [desi_content] => 红色烤漆 [desi_pnum] => 002 [tid] => 1 [image] => http://cphz.hichina.com/images/150x60.jpg ) )


转化后 需要得到PHP code


Array ( [desi_1] => Array ( [desi_id] => 1 [desi_name] => 黑色 [desi_price] => 0 [desi_type] => 1 [desi_content] => 黑色黑色黑色 [desi_pnum] => 001 [tid] => 1 [image] => http://cphz.hichina.com/images/base_mg02.gif ) [desi_2] => Array ( [desi_id] => 2 [desi_name] => 红色 [desi_price] => 200 [desi_type] => 1 [desi_content] => 红色烤漆 [desi_pnum] => 002 [tid] => 1 [image] => http://cphz.hichina.com/images/150x60.jpg ) [desi_3] => Array ( [desi_id] => 3 [desi_name] => 红色 [desi_price] => 200 [desi_type] => 1 [desi_content] => 红色烤漆 [desi_pnum] => 002 [tid] => 1 [image] => http://cphz.hichina.com/images/150x60.jpg ) )



用什么方法转呢 求高手解答

作者: ikenbor   发布时间: 2011-11-29

真蛋痛,看了半天恶心的条状数组...

是不是就是 [0] 变成 [desi_1] [1] 变成 [desi_2]?

作者: PhpNewnew   发布时间: 2011-11-29

是的 0变成 [desi_1] 这个数字是和 子数组 [desi_id] => 1 的desi_id的值对应 

辛苦你了 兄弟

作者: ikenbor   发布时间: 2011-11-29

刚吃饭老,应该还有更好的方法,先这样吧.
PHP code

$array=array(Array ( 'desi_id' => 1,'desi_name'=>'黄色'),
Array ( 'desi_id' => 2,'desi_name'=>'黑色'),
Array ( 'desi_id' => 3,'desi_name'=>'红色')
);
$NObj=new ArrayObject($array);
$NewObj=array();
foreach ($NObj as $Key=>$Value){
    $NewKey=$Key+1;
    $NewObj['desi_'.$NewKey]=$Value;
}
print_r($NewObj);

作者: PhpNewnew   发布时间: 2011-11-29

foreach($ar as $v)
  $r['desi_' . $v[desi_id]] = $v;

print_r($r);

作者: xuzuning   发布时间: 2011-11-29

PHP code
<?php
$arr = array();
$arr[] = 'test1';
$arr[] = 'test2';
$arr[] = 'test3';
//arr数组:array(0=>test1 , 1=>test2 , 2=>test3)
foreach ($arr as $key=>$val){
    unset($arr[$key]);
    $arr['desi_'.($key+1)] = $val;
}

//现在arr数组:array(desi_1=>test1 , desi_2=>test2 , desi_3=>test3)

?>


这个不会新建数组,而是在原有数组上直接改动。

作者: hellodifa   发布时间: 2011-11-29

相关阅读 更多