简体   繁体   中英

Why doesn't my php function return a json formatted value?

I am trying to store a couple of form fields in a mysql database. These specific fields can have multi selected values. So i like to store the value as json_encode formatted value.

Now when I code per form field i can store the values in json format in the mysql db. Because of the repetitions i tried this function but this returns an array

function radioValue($radiodata) {
    $tmpArray = array();
    $tmpArrayLen = count($radiodata);
    for ($i = 0; $i < $tmpArrayLen; $i++) {
        $tmpArray[$i] = $radiodata[$i];
    }
    $tmpValue = json_encode($tmpArray);
    return $tmpValue;
}

So not {"1":"value1"} but ["value1"]

What have I overlooked??

btw this is the part why worked for each field

$tmpArray = array();
        $len = count($posted_data["field1"]);
        for ($i = 0; $i < $len; $i++) {
            $tmpArray[$i] = $posted_data["field1"][$i];
        }
        $storeValue = json_encode($tmpArray);

You have to decode it after you encode:

$futureArray = radioValue($radiodata);

$array = json_decode($futureArray);

Also, add a true as the second parameter and it will be a associative array

$array = json_decode($futureArray, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM