Search code examples
phparraysjsonwordpressconverters

How to convert simple php array into json data with heads


I am getting post object data in WordPress, and here is my code

$pre_items = get_post_meta( $post_object->ID, 'rudr_select2_tags');

The print_r provide me this data

Array ( [0] => Array ( [Apple iPhone 5,Apple iPhone 6] => 1 ) )

I have written the below code

  $pre_items = get_post_meta( $post_object->ID, 'rudr_select2_tags');
  $new_arr = array();

  foreach($pre_items as $arr){
    $process_array = array();
    $process_array['id'] = $arr;
    $process_array['name'] = $arr;
    array_push($new_arr,$process_array);
   }

   $items = json_encode($new_arr);  

but this code returns data

[{"id":{"Apple iPhone 5,Apple iPhone 6":1},"name":{"Apple iPhone 5,Apple iPhone 6":1}}]

But I want data in the below format

[{id: Apple iPhone 5, name: "Apple iPhone 5"},
{id: Apple iPhone 6, name: "Apple iPhone 5"}
]

Please help how to acheive this.


Solution

  • Add the third paramater to get_post_meta to toggle return of a single value, and explode the array key to seperate the devices in order to structure the data as per your example.

    $pre_items = get_post_meta( $post_object->ID, 'rudr_select2_tags', true);
    $new_arr = array();
    
    foreach($pre_items as $key => $value ){
    
        // Split key into array.
        $devices = explode( ',', $key );
    
        // name is set to first device.
        $name = $devices[0];
    
        foreach ( $devices as $device ) {
            $process_array = array(
                'id' => $device,
                'name' => $name,
            );
            array_push($new_arr, $process_array);
        }
    
    }
    
    $items = json_encode($new_arr);