开发者

Creating new assoc array from key => values of other arrays

开发者 https://www.devze.com 2023-02-07 23:06 出处:网络
object(stdClass)#25 (7) { [开发者_StackOverflow中文版\"store_id\"]=> string(2) \"27\" [\"account_id\"]=>
object(stdClass)#25 (7) {
    [开发者_StackOverflow中文版"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']


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.


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'].

0

精彩评论

暂无评论...
验证码 换一张
取 消