0

Within the wp_posts WordPress table, I have a row stored for a post (custom post type) that literally stores the following within the post_content column:

Array
(
    [test_price] => 39.00
    [test_elegibility] => Eligible
    [test_confirmation] => confirmed
    [test_id] => DUA6A44THQH7U
    ...
)

When I query the table via the following:

$query = $wpdb->get_results( 'SELECT * FROM wp_posts where post_type = "custom_post_type"' );

foreach($query as $q) {
    $content = $q->post_content;
    var_dump($content);
}

The result of the var_dump for each variable above is obviously as follows:

string(1369) string(1311) 

and so on since the post_content field, which is essentially saved as a string for my purposes at the moment, contains the array I'm trying to pull out.

I know I can strip / filter out the brackets, square brackets, etc and cycle through each instance to create an associative array directly from the post_content field value quite easily, which is fine.

My question is, am I missing a trick where I can simply assign the strings as arrays immediately by simply assigning them to variables? For example, using the above:

foreach($query as $q) {
    $content = $q->post_content;
    var_dump($content);
}

The result would be that each var_dump should ideally print out:

array(2) { 'te' => string(4) "werg" 'wreg' => string(6) "werefg" }

NOTE - the field values will only ever contain the arrays, there's nothing else appended or prepended...

1
  • If I understand your question, you can serialize the array while saving the data in post_content field and then unserialized it when you are rendering. But the best option is to use postmeta table for your custom requirements. Commented May 8, 2017 at 14:50

1 Answer 1

1

Looks like you probably want to use the PHP serialize method which will return a string representation of your array that you can then store in the database. You can then use unserialize to get the data out of the string again.

If you're desperate for a way to reparse a var_dump output to an array you can check out this answer https://stackoverflow.com/a/3531880/7326037 but it's not pretty.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer - in the end I did use serialize, among a couple of other things too!

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.