开发者

Write an array to config in Codeigniter?

I'm working with a config file that I have create in order to sto开发者_运维百科re users. This surely wasn't what the configs were intended to be used for, but it's an extremely small application and I think that it would be a nice solution.

My array looks like this:

$config['users'] = array(array('username' => 'username', 'password' => 'password'));

This works well. I can retrieve the information quick and easy. BUT, if I try to write a new array (a new user) to the config file I get this error: Illegal offset type in isset or empty

I'm using $this->config->item('users', array('username' =>....)) which doesn't appear to support arrays.

How can I write arrays to my config variable? Is there another way?

EDIT: Alright, the error is fixed thanks to the answer given by phirschy. I was so sure in my head that I could use config->item() that I didn't check the manual for a config->set_item()... BUT, it still doesn't work. Here is the specific code:

        $users = $this->config->item('users');
        array_push($users, array('username' => $this->input->post('username'), 'password' => $this->input->post('password')));
        $this->config->set_item('users', json_encode($users));
        echo json_encode($users);

This code is called via Ajax, and I have an alert box to see if it the values are correct. They are. And as you can see, I've tried storing it as json instead of array as well.... but that doesn't work either. Help please?

thank you


You have to use the 'set_item' method to write a config item, not 'item':

$this->config->set_item('item_name', 'item_value');

Or in your case:

$this->config->set_item('users', array(...));


Old question, but I had a similar question. So:

And as you can see, I've tried storing it as json instead of array as well.... but that doesn't work either.

That should have been the first thing to tip you off that something else was amiss - JSON is just a string. If you weren't able to store that, something else was wrong. Indeed your code is confusing and a bit suspect, you're storing JSON (a string) but you're accessing it as if it's an array (no json_decode anywhere).

Anyway, I'd suggest a simple test:

$this->config->set_item('the_array', array("I'm", "an", "array"));
echo 'The config array: '.print_r($this->config->item('the_array'), true);

I ended up trying this myself after seeing your question with a definitive answer - works fine in CodeIgniter 1.7. So the answer is, yes, can store arrays as config items. No JSON-encoding required.

Cheers

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜