0

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
1
  • 2
    Just use $data["the_string_you_want"] = array(...); Commented Jul 24, 2012 at 9:32

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

Use

$data["the_string_key"] = array(
 //...
);
answered Jul 24, 2012 at 9:33

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.