Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: setting a number as key in associative array

Tags:

json

arrays

php

I'm trying to recreate json from a DB, for the client side. Unfortunately some of the keys in the json are numbers, which work fine in javascript, however as a result PHP keeps treating them as numeric instead of associative arrays. each key is for a document. let me show you:

PHP:

  $jsonobj;
  while ($row = mysql_fetch_assoc($ms)) {

            $key = strval($row["localcardid"]);
            $jsonobj[$key] = json_decode($row["json"]);
    }
    // $jsonobj ist still a numeric array
    echo json_encode($jsonobj);

the resulting json should look like this:

{
  "0": {
    "terd": "10",
    "id": 0,
    "text": "",
    "pos": 1,
    "type": 0,
    "divs": [
        {},
        {}
    ],
    "front": 1
 }
"1": {
     "terd": "10",
    "id": 0,
    "text": "",
    "pos": 1,
    "type": 0,
    "divs": [
        {},
        {}
    ],
    "front": 1
  }
}

One obvious solution would be to save the whole json without splitting in up. however that doesnt seem wise in regards to the db. i wanna be able to access each document seperately. using

 $jsonobj = array ($key => json_decode($row["json"]));

obviously works, but unfortunately just for one key...

EDIT: for clarification* in php: there's a difference between

array("a", "b", "c")      

and

   array ("1" => "a", "2" => "b", "3" => "c").

the latter, when done like this $array["1"] = "a" results in array("a") instead of array("1" => "a")

ANSWERED HERE

like image 248
jcfrei Avatar asked May 29 '26 11:05

jcfrei


2 Answers

Try

echo json_encode((object)$jsonobj);
like image 138
Vatev Avatar answered Jun 01 '26 00:06

Vatev


I believe if you pass the JSON_FORCE_OBJECT option, it should output the object with numeric indexes like you want:

$obj = json_encode($jsonObj, JSON_FORCE_OBJECT);

Example:

$array = array();

$array[0] = array('test' => 'yes', 'div' => 'first', 'span' => 'no');
$array[1] = array('test' => 'no', 'div' => 'second', 'span' => 'no');
$array[2] = array('test' => 'maybe', 'div' => 'third', 'span' => 'yes');

$obj = json_encode($array, JSON_FORCE_OBJECT);
echo $obj;

Output:

{
    "0": {
        "test": "yes",
        "div": "first",
        "span": "no"
    },
    "1": {
        "test": "no",
        "div": "second",
        "span": "no"
    },
    "2": {
        "test": "maybe",
        "div": "third",
        "span": "yes"
    }
}
like image 20
drew010 Avatar answered Jun 01 '26 01:06

drew010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!