Skip to content
Advertisement

php array to json with index keys(without json droping the keys)

hi I’m trying to return a JSON response with PHP and i need my array to have numeric keys but when i use array_values JSON drops the key and it only returns the value

$diffFinal = array_values($diffArray);

but my json is :

"diff": [
  "2 days ago",
  "35 days ago",
  "67 days ago",
  "98 days ago",
  "129 days ago",
  "189 days ago",
  "220 days ago",
  "255 days ago",
  "288 days ago",
  "322 days ago",
  "351 days ago",
  "415 days ago",
  "463 days ago",
  "509 days ago",
  "510 days ago"
]

and i want to be like

    "diff": [
  "1" : "2 days ago",

I’ve read some things about JSON, that it does this, but is there any way that i can do it? Thank you, all help are appreciated

Advertisement

Answer

This just adds a new element at the start and then unsets it, this means that the array starts from 1 instead…

$diffFinal = array_values($diffArray);
array_unshift($diffFinal,null);
unset($diffFinal[0]);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement