-1

I am working in PHP and have an issue with json_encode(). The process wipes the inital "key" that was set by the "array_values" command as shown below.

array(1) { 
    [0]=> array(5) { 
        ["ID"]=> string(4) "2679" [
        "PackageName"]=> "Update for Windows 8.1 for x64-based Systems (KB2965065)" 
        ["Description"]=> string(262) "Install this update to resolve issues in Windows." 
        ["KB"]=> string(7) "2965065" 
        ["Repo"]=> string(21) "Windows Update Server" 
}

$packages = array_values($this->control->fetchPackageTables($this->input->get("platform")));             

[
    {
        "ID":"2679",
        "PackageName":"Update for Windows 8.1 for x64-based Systems (KB2965065)",
        "Description":"Install this update to resolve issues in Windows.", 
        "KB":"2965065",
        "Repo":"Windows Update Server"
    }
]

I have tried looping with a foreach through the array and setting a number but it still gets dropped. Any ideas?

Thanks!

5
  • 1
    array_values dont set anything, it just return values of an array. Remove array_values and You gonna have that key. Commented Jul 22, 2014 at 15:30
  • 1
    I didnt get it, what is it dropping. what is the initial key in question Commented Jul 22, 2014 at 15:30
  • Where do you call json_encode(). Commented Jul 22, 2014 at 15:31
  • 1
    pretty much the sole purpose of array_values is to strip off the keys and return a numbered array Commented Jul 22, 2014 at 15:32
  • 2
    Your JSON is 100% correct. It is exactly as it should be. [] is an array in JSON. Arrays are numeric, and automatically start at 0. Commented Jul 22, 2014 at 15:34

3 Answers 3

3

JSON does not support associative arrays.

Arrays in JSON / Javascript consist only of numbered indexes. Associative arrays will be converted to objects/properties.

There is nothing getting dropped. [ ] indicates an array. { } indicates an object. You have one object in the array.

3

I'm adding this as an answer as I currently can't comment, and was helpful for myself. If you find that a segment of your json is being encoded as an array instead of an object (e.g.:the key's are being dropped).

You can add JSON_FORCE_OBJECT like this: json_encode($foo,JSON_FORCE_OBJECT); This will force everything to be encoded as an object, preserving all keys.

You can find more flags here: http://php.net/manual/en/function.json-encode.php

0
0

I believe the reason why it is dropping the indexes is because they are indexed by number so when encoding it just thinks it does not need the keys you could try making your keys into strings as opposed to integers so the encoding doesn't wipe them.

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.