1
object(stdClass)#25 (7) {
    ["store_id"]=>
        string(2) "27"
    ["account_id"]=>
        string(1) "5"
    ["store_date_created"]=>
        string(19) "2011-01-31 02:40:38"
    ["options"]=>
        array(2) {
          [0]=>
            array(2) {
                ["key"]=>
                  string(5) "state"
                ["value"]=>
                  string(2) "FL"
        }
          [1]=>
            array(2) {
                ["key"]=>
                  string(7) "zipcode"
                ["value"]=>
                  string(5) "12343"
        }
   }
}

I have this object structure for a Store and one of its attributes is an assoc. array of options (pulled from a DB). There can be zero to many options, but key will always be unique. I need a way to take the options assoc. array and turn it into something like this:

["options"]=>
    array(1) {
      ["state"] => "FL",
      ["zipcode"] => "12343"
    }

Don't know if my syntax is correct for the result I want but I basically want to do:

echo $store_obj->options['state']

2 Answers 2

4

Assuming that options is in $object->options:

$newOptions = array();    
array_walk($object->options, function($opt) use (&$newOptions) {
   list($key, $value) = $opt;
   $newOptions[$key] = $value;    
});
$object->options = $newOptions //reasing filtered options to options property

Note: When using code in that form PHP 5.3 is needed.

Sign up to request clarification or add additional context in comments.

Comments

3

Let's say the object is called $store_obj.

$store = array();
foreach($store->options as $opt){
  $store_obj[$opt['key']] = $opt['value'];
}
$store_obj->options = $store;

Now you should be able to echo $store_obj->options['state'].

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.