Welcome Guest, Not a member yet? Register   Sign In
Entity JSON encode and manually decode
#1

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.
Reply
#2

That's not in json format, that's encoded with serialize(). You need to use unserialize() to decode it back to an array.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

(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
Reply
#4

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?
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#5

(This post was last modified: 04-18-2021, 11:52 AM by InsiteFX.)

A PHP json_encode array conversion example

PHP | json_encode() Function
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB