php超简单的数组转对象,对象转数组

数组转对象


$a = array(1,2,4,'ff'=>array('a'=>array(3,2,5),'j',3));
foreach($a as $key => $val) {
    if (is_array($a[$key])){
         $a[$key] = (object)$a[$key];
    }
    if (is_array($val)) {
          foreach($val as $k => $v) {
            if (is_array($val[$k])){
             $a[$key]->$k = (object)$val[$k];
            }
        }
  
    }
}
$b = (object)$a; 
print_r($b);

对象转数组

if(is_object($b)) {
    foreach($b as $keyobj => $valobj) {
        
        if (is_object($b->$keyobj)) {
         
            $b->$keyobj = (array)$b->$keyobj;
        }
        if (is_object($valobj)) {
            foreach($valobj as $kobj => $vobj) {
                if (is_object($valobj->$kobj)) {
                     $b->$keyobj[$kobj] = (array)$valobj->$kobj;
                }
            }
        }
        
    }
}
$c = (array)$b;
print_r($c);

你可能感兴趣的:(php)