-3

In Wordpress, I have some post meta_key fields with strings of this form, from an serialized array, with a variable length:

a:2:{i:0;i:281;i:1;i:282;}

I need to copy them to other post meta_key fields, but in this format:

[281,282]

How can I do this?

My code:

$attachments = get_posts( $args );
if ($attachments) {
   $attachmentIds = array();
   foreach ( $attachments as $attachment ) {
      $attachmentIds[] = $attachment->ID;
   }
}

$data['meta_input']['advert_post_attachments'] = $attachmentIds;

P.S. I apologize to those who were angry with my question! I am not a PHP programmer, I'm really not a programmer at all, but I need to solve this.

I checked the recommended by @Machavity answers, they are very educational, but this doesn't helped me to solve my problem.

[SOLVED]

I thank everyone who tried to help me: @AbraCadaver, @Anant, @ManinderpreetSingh, @ShaktiPhartiyal and, sure, @Machavity! :)

Yurié
  • 2,148
  • 3
  • 23
  • 40

2 Answers2

2

You have to use the unserialize() function and then join the output to create an array like format: You can use:

<?php
$sData = 'a:2:{i:0;i:281;i:1;i:282;}';
$uData = unserialize($sData);
$arrFormat = "[".implode(",",$uData)."]";
echo $arrFormat;

this will give you the output:

[281,282]
Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
0

Here is a working solution that I found in a Wordpress plugin:

...

$attachments = get_posts( $args );
if ($attachments) {
   $attachmentIds = array();
   foreach ( $attachments as $attachment ) {
      $attachmentIds[] = $attachment->ID;
   }

$dirty_ordered_keys = $attachmentIds;
$length = sizeof($dirty_ordered_keys);
$clean_ordered_keys = array();

for ( $i = 0; $i < $length; $i++ ) {
    $clean_ordered_keys[$i] = intval($dirty_ordered_keys[$i]);
}

$clean_ordered_keys_json = json_encode($clean_ordered_keys);
$data['meta_input']['advert_post_attachments'] = $clean_ordered_keys_json;
Yurié
  • 2,148
  • 3
  • 23
  • 40