I'm new to json. I have existing json data in a file. here it looks like:
{
"qwqw":{
"id":3,
"item1":{
"id":15,
"price":31.85
},
"item2":{
"id":17,
"price":26
},
"item3":{
"id":16,
"price":57.85
}
}
}
I can get this value using json_decode. I will add another entry using this code.
$data = json_decode( file_get_contents('test.ini'), true );
$data[] = array(
'id'=>4,
'item1'=>array(
'id'=>15,
'price'=>11
),
'item2'=>array(
'id'=>17,
'price'=>12
),
'item3'=>array(
'id'=>16,
'price'=>13.50
)
);
file_put_contents('test.ini', json_encode($data) );
This works properply. When I decoded it again. this how it looks.
{
"qwqw":{
"id":3,
"item1":{
"id":15,
"price":31.85
},
"item2":{
"id":17,
"price":26
},
"item3":{
"id":16,
"price":57.85
}
},
"0":{
"id":3,
"item1":{
"id":15,
"price":11
},
"item2":{
"id":17,
"price":12
},
"item3":{
"id":16,
"price":13.5
}
}
}
My problem is, can I change the value "0" ? to a string.
anyone who can help ?
asked Jul 24, 2012 at 9:30
justin
1,7196 gold badges21 silver badges25 bronze badges
-
2Just use $data["the_string_you_want"] = array(...);yent– yent2012年07月24日 09:32:42 +00:00Commented Jul 24, 2012 at 9:32
3 Answers 3
0 is a string here, you can tell because it has quotes around it.
But if you want a different string, don't use:
$data[] = array(
/* ... */
)
but:
$data['myKey'] = array(
/* ... */
)
answered Jul 24, 2012 at 9:32
Evert
101k18 gold badges136 silver badges221 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use
$data["the_string_key"] = array(
//...
);
answered Jul 24, 2012 at 9:33
xdazz
161k38 gold badges255 silver badges278 bronze badges
Comments
yes you can
$data['string'] = array(
'id'=>4,
'item1'=>array(
'id'=>15,
'price'=>11
),
'item2'=>array(
'id'=>17,
'price'=>12
),
'item3'=>array(
'id'=>16,
'price'=>13.50
)
);
justin
1,7196 gold badges21 silver badges25 bronze badges
answered Jul 24, 2012 at 9:32
swapnilsarwe
1,3001 gold badge8 silver badges13 bronze badges
Comments
lang-php