0

How do I convert an array of arrays into an array of objects?

$a = blah // an array of arrays;

$b= (object) array( $a);

print_r($b); //prints an object of an array of arrays
6
  • 1
    Note that "associative array" does not mean "array of arrays". Commented Jan 16, 2011 at 18:34
  • Why do you need it to declare itself an object if it is already a key-value thing? I mean, isn't that enough? You can already refer to stuff in there with $var[$n]['key']. Commented Jan 16, 2011 at 18:34
  • What you are talking about is not associative arrays but multidimensional arrays. Associative arrays is just like a map/dictionary. Commented Jan 16, 2011 at 18:34
  • Wait, what? You have an array of arrays that you want to convert to an array of objects but you want $b to be an object of arrays of arrays— *head asplode* Commented Jan 16, 2011 at 18:37
  • I am using the php file for a flex project, which expects an array of objects. Flex is somewhat retarded and specific Commented Jan 16, 2011 at 18:38

2 Answers 2

3

An associative array is not an array of arrays. It is an array whose keys are strings. An array of arrays is a multidimensional array.

To convert a multidimensional array into an array of objects, convert each item into an object:

foreach(array_keys($a) as $key)
{
  $a[$key] = (object)$a[key];
}
Sign up to request clarification or add additional context in comments.

Comments

0

try

$array = associative array

$object = new StdClass();

foreach ( $array as $key => $value ){
    $object -> $key = $value;
}

print_r ($object);

this is for a single dimensional array. if its multi dimensional then you need to change it into a recursive function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.