Reputation: 89
I'm busy attempting to pull particular data from a serialized string in the WP database. The raw string looks like this:
{"params":{"1":{"key":"1","enabled":"1","value":"Yes"},"2":{"key":"2","enabled":"1","value":"No"}}}
I am able to (apparently) retrieve this string with the following code:
$results = $wpdb->get_var("SELECT options FROM wp_wpl_dbst WHERE table_column = '{$id}'");
$parseme = unserialize($results);
However, I am unable to actually pull any values from the array I've apparently just created.
I tried some variations of the following code, all of which result in the same error:
foreach ($parseme as $parsed) {
$return_string .= $parsed['key'] . '<br>';
$return_string .= $parsed['value'] . '<br>';
}
The error is:
Warning: Invalid argument supplied for foreach() in /usr/www/users/.../functions.php on line 236
Any input will be much appreciated.
Upvotes: 0
Views: 1204
Reputation: 36
The String is JSON
{"params":{"1":{"key":"1","enabled":"1","value":"Yes"},"2":{"key":"2","enabled":"1","value":"No"}}}
We can use json_decode to cover into the object, try this
$results = $wpdb->get_var("SELECT options FROM wp_wpl_dbst WHERE table_column = '{$id}'");
$parseme = json_decode($results);
Upvotes: 0
Reputation: 13850
The raw string you're showing isn't a serialized string. A serialized string has key lengths in it and looks like this: a:2:{i:0;s:4:"test";i:1;a:2:{i:0;s:4:"test";i:1;R:3;}}
. What you're retrieving is actually JSON
.
So you should be able to replace unserialize($results)
with json_decode( $results, true )
and then you'll have access to an associative array. Note that you still have an outer array with the params
key. Take the below code for example
$results = '{"params":{"1":{"key":"1","enabled":"1","value":"Yes"},"2":{"key":"2","enabled":"1","value":"No"}}}';
$results_array = json_decode( $results, true );
$return = '';
foreach( $results_array['params'] as $array ){
$return .= $array['key'].'<br>';
$return .= $array['value'].'<br>';
}
This will output the following:
string(23) "1
Yes
2
No
"
Upvotes: 1