CodeIgniter Forums
Entity JSON encode and manually decode - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: Entity JSON encode and manually decode (/thread-79087.html)



Entity JSON encode and manually decode - ipmeel - 04-18-2021

In entity
Code:
protected $casts = [
    'courses'        => 'array',
    'courses_object' => 'json',
    'courses_array'  => 'json-array',
];
The posted array
Code:
courses = array{"bsc-bio", "bsc-bed", "bca"}
It inserted in database as
Code:
"a:3:{i:0;s:7:"bsc-bio";i:1;s:7:"bsc-bed";i:2;s:3:"bca";}"
How to manually decode it?
Code:
json_decode('a:3:{i:0;s:7:"bsc-bio";i:1;s:7:"bsc-bed";i:2;s:3:"bca";}')
json_decode() returns NULL.


RE: Entity JSON encode and manually decode - includebeer - 04-18-2021

That's not in json format, that's encoded with serialize(). You need to use unserialize() to decode it back to an array.


RE: Entity JSON encode and manually decode - ipmeel - 04-18-2021

(04-18-2021, 09:15 AM)includebeer Wrote: That's not in json format, that's encoded with serialize(). You need to use unserialize() to decode it back to an array.
Got it! Thanks.
The unserialize() worked perfectly.
But I am having following code in my Entity...
PHP Code:
protected $casts = [
    
'courses'        => 'array',
    
'courses_object' => 'json',
    
'courses_array'  => 'json-array',
]; 
The CodeIgniter is using word 'json' here? Exclamation


RE: Entity JSON encode and manually decode - includebeer - 04-18-2021

I don't know, I never used this feature. But 'courses' is cast to 'array', not 'json', maybe that's why it's serialized and not encoded in json?


RE: Entity JSON encode and manually decode - InsiteFX - 04-18-2021

A PHP json_encode array conversion example

PHP | json_encode() Function