0

I have a json array storred in a file looking like:

["bla bla","bla bla2","bla bla3"]

And if I want to remove one of these objects from the json array with the code below the json converts to another type of array looking like:

{"1":"bla bla","2":"bla bla2","3":"bla bla3"} 

I dont want this to happen because it screws up code in another place. How can I achieve this?

$eng = json_decode($en_banners, false);

unset($eng[$id]);

$myFile = "languages/banners.php";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "<?php \$de_banners='".json_encode($eng)
2
  • Based on your usage, you might have better luck with var_export. Commented Nov 13, 2012 at 8:40
  • Try json_decode($blah, true) - parse JSON as assoc array and not object. Commented Nov 13, 2012 at 8:41

2 Answers 2

2

JavaScript arrays are zero-based so there's no possible way to create a JavaScript array from a PHP array with gaps unless you fill the gaps:

$en_banners = '["bla bla","bla bla2","bla bla3"]';
$eng = json_decode($en_banners, false);
var_dump($eng);
$id = 0;
$eng[$id] = null; // Rather than: unset($eng[$id]);
var_dump(json_encode($eng));

If array keys are not relevant, you can simply ignore them:

$en_banners = '["bla bla","bla bla2","bla bla3"]';
$eng = json_decode($en_banners, false);
var_dump($eng);
$id = 0;
unset($eng[$id]);
var_dump(json_encode(array_values($eng)));

If none of these solutions apply, we need more data :)

Sign up to request clarification or add additional context in comments.

2 Comments

The first one makes the array post stay but with a null value. But the second one works very well! Thanks! :)
That's because you cannot have gaps! Glad it helped.
1

Set at your json_decode false to true.. If its false the decoder makes php Object, if its true it makes PHP Array from that json..

$eng = json_decode($en_banners, TRUE);

After that json_encode convert php Object to json Object, php Array to json Array..

P.S

after unset add...

    $eng = array_values($eng);

To cleanup array keys

$eng = json_decode($en_banners, TRUE);

unset($eng[$id]);
$eng = array_values($eng);
$myFile = "languages/banners.php";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "<?php \$de_banners='".json_encode($eng);

7 Comments

Nope, the problem is still there! :(
Looks like this should work. There might be some magic happening if you are accessing $eng['some_string'] to turn it into an object.
@bdares at the example its $eng[$id] so I don't think for strings :)
This doesn't work because there's no consecutive index anymore.
@DanLee I tested it and it works as it wanted.. and did you test it?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.