Data access in WP using PHP

Objective and raw data

Obtaining a raw data created by WP forms from database

  $result = $wpdb->get_results( $wpdb->prepare("
      SELECT `Position`
      FROM `wp_meta`
      WHERE `post_id` = %d
    ", $post_id,
    )
    

By using either vardump or print_r, we can view the raw data as follows:

var_dump($result);

array(1) {
    [
        0
    ]=>
  object(stdClass)#6751 (1) {
        [
            "Position"
        ]=>
    string(207) "{"address":"Opp Seletar Airport, Singapore","lat":1.4208723379839088,"lng":103.86265088778731,"zoom":18,"place_id":"ChIJeVt1C0oU2jERl9Y4zZM8jdg","city":"Singapore","country":"Singapore","country_short":"SG"}"
    }
}

print_r($result);

Array
(
    [
    0
] => stdClass Object
        (
            [Position
] => {
    "address": "Opp Seletar Airport, Singapore",
    "lat": 1.4208723379839088,
    "lng": 103.86265088778731,
    "zoom": 18,
    "place_id": "ChIJeVt1C0oU2jERl9Y4zZM8jdg",
    "city": "Singapore",
    "country": "Singapore",
    "country_short": "SG"
}
        )

)

The raw data contains JSON embedded within an array.

To access the array

First we must determine the type of data that is being presented.

gettype($result);

echo gettype($result);
//return Array

some part of the result maybe object -> property or element [key] [value]

echo gettype($result[0]);
//return Object
echo gettype($result[0]->Position);
//return String

Refine the result and retrieve specific data

After obtain the embedded json from raw data as string, we can now further process the data into accessable array

$resultdata = stripslashes_deep($positionValue);
$jsonPos = json_decode($resultdata);

from this format:

{
    "address": "Opp Seletar Airport, Singapore",
    "lat": 1.4208723379839088,
    "lng": 103.86265088778731,
    "zoom": 18,
    "place_id": "ChIJeVt1C0oU2jERl9Y4zZM8jdg",
    "city": "Singapore",
    "country": "Singapore",
    "country_short": "SG"
}

into

stdClass Object
(
    [address
] => Opp Seletar Airport, Singapore
    [lat
] => 1.4208723379839
    [lng
] => 103.86265088779
    [zoom
] => 18
    [place_id
] => ChIJeVt1C0oU2jERl9Y4zZM8jdg
    [city
] => Singapore
    [country
] => Singapore
    [country_short
] => SG
)

Hence now we can access individual property using the following:

echo $jsonPos->lat;
//return 1.4208723379839
echo $jsonPos->lng;
//return 103.86265088779