본문 바로가기

Programming/PHP

배열 stdclass <-> array 변환

배열 stdclass <-> array 변환

그게 바로 stdClass 때문인데.. 

stdClass = 문자열인덱스 배열 구조라고 한다.

예) a -> val = "value";


---------------------------------------------------------------------------

stdClass 는 Json 을 사용할때도 사용 되기도 한다.
스크립트에서 ajax 사용시 넘기는 데이터 타입을 json 으로 지정하면
넘어가는 데이터가 stdClass로 넘어간다.

이럴경우 일반 배열로 다시 변환 하고 싶다면...

json_decode($aa,true); 로 선언하면 된다.

---------------------------------------------------------------------------

자.. 이제 본론이다.

stdClass -> Array 로 바꾸는 법.

<?php
 
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
 
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
 
?>
----------------------------------------------------------------------------
Array -> stdClass


<?php
 
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
}
else {
// Return object
return $d;
}
}
 
?>
------------------------------------------------------------------------------

예제 

// Create new stdClass Object
$init = new stdClass;
 
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
 
// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);
 
// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);
--------------------------------------------------------------------------------

더보기



1차는 배열이고 2차가 클래스 오브젝트일경우 선택하는 방법
오류 표시 : Cannot use object of type stdClass as array
<?
Array ( 
[0] => stdClass Object ( 
[comment_id] => 158 
[posting_id] => 208 
[writer_id] => chongmoa 
[writer_name] => 총모아 
[comment] => 좋아좋아 
[reg_date] => 20140211171220 ) 

[1] => stdClass Object ( 
[comment_id] => 159 
[posting_id] => 208 
[writer_id] => chong 
[writer_name] => 마이 
[comment] => 굿 
[reg_date] => 20140211171222 )
)
echo $comment_data[1]->comment_id;