0

I have a multidimensional associative JavaScript array with some metabox data and I need to store that array in the WordPress database (in a single column).

And I also want to get that stored array back in the metabox call back function and use the values in the array to populate the relevant fields.

This is what I've done so far...

    var data = [
        { key: 'cardK', val: 13 },
        { key: 'cardQ', val: 12 },
        { key: 'cardAJ', val: 11 },
    ];
    var serializedData= JSON.stringify( data );

This outputs a string look like this

[[1,2],[3,4],[5,6]]

Now I can store this in the DB in a single column. But how can I get this back as an array and use it to populate the fields ?

3
  • json_decode() on php side or JSON.parse() on client side Commented Jan 16, 2016 at 16:23
  • NB: That is not an "associative" array. It's just an array. In JavaScript an associative array is an object hash, which is a different animal. Commented Jan 16, 2016 at 16:34
  • Thanks I updated the code Commented Jan 16, 2016 at 16:45

1 Answer 1

3

Save the string as JSON, like this:

var data = [[1,2],[3,4],[5,6]];
var serializedData = JSON.stringify(data);

Before you convert make sure you replace any data which has changed in the json to make it valid json before using json_decode().

use this function:

str_replace();

To convert it into array on PHP side:

json_decode(data, true); // returns array
json_decode(data); // returns an object, not an array.

When you get the JSON string back from MySQL, you can turn it back into an array with JSON.parse(), like this:

var returnedArr = JSON.parse(returnedData);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, Is there a way I can use this serialized string and convert it into a PHP array ?
@TharinduLucky use json_decode() on php side to change it into a array
Thanks I tried this, json_decode(data, true); method but it returned null when I var_dump it... I checked the DB and I can see a new record has been added it looks like a serialized string. But, why this is not coming back as an array ? Check this snapshot link
@TharinduLucky Would you like to continue this chat in chatroom?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.