0
$myArray = array();

for($i=0;i<2;$i++){
..
.. //get the content logic here

assign it to array
$myArray["item"]["content"] = $item_content;
}
echo json_encode($myArray);

The above code produced this result:

enter image description here

Which has an error because I didn't merge them.

I tried to merge like this:

$finalJson = array_merge($finalJson, $myArray); 

but the output of echo $finalJson is one object instead of 3.

LoveFortyDown
  • 1,011
  • 2
  • 17
  • 37
jamie eason
  • 141
  • 10

3 Answers3

1

Update:

Your real problem is down to your use of array_merge on an associative array. The behaviour of array_merge is to reassign duplicate keys if they are associative (cf the docs):

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

And because $myArray is clearly using strings as keys, the values in $finalJson are being reassigned. What you need to do is either create unique keys on each iteration, or simply push the values of $myArray onto a numerically indexed $finalJson array (like I showed in my original answer below)


The problem is simply this:

$myArray["item"]["content"] = $item_content;

it's inside the loop, each time reassigning the value of $myArray["item"]["content"], and not adding it to the array. I suspect that what you wanted to do is add this at the bottom of your loop (for each new value of $myArray):

$finalJson[] = $myArray;

Then, on the next iteration, $myArray will be reassigned, and its new value will be appended to the $finalJson variable.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • hey this worked! do you know how to calculate the number of items (javascript). I tried data.item.length it can't work. – jamie eason Jan 05 '15 at 12:51
  • 1
    since `$finalJson` is now a numerically indexed array, you can just write `data.length`. For objects, you could use `Object.keys(anObject).length` or `var i=0, p; for (p in object) { if (object.hasOwnProperty(p)) ++i; } console.log(i);` – Elias Van Ootegem Jan 05 '15 at 12:53
  • 1
    @jamieeason: is that possible? Remember: JS arrays are sparse (`var anArray = [1, 2, 3];` will have 3 lenght, `anArray[123] = 4;` results in `anArray.length` being 124, even though only 4 keys are set – Elias Van Ootegem Jan 05 '15 at 13:02
  • so what should I do in my case? I tried data['item'].length and data.length, both doesn't work. – jamie eason Jan 05 '15 at 13:06
  • 1
    @jamieeason: `data` is an array, not an object, so `data['item']` won't work (it's the same as `data.item`). Instead check your console, and log the variable `console.log(data)`, look what its value actually is and try to work out why you get the behavior you're seeing (perhaps it _is_ an object, but it has a `length` property of its own?) – Elias Van Ootegem Jan 05 '15 at 13:24
  • 1
    @jamieeason: It's not a bunch of text, it's a JSON string, you'll have to parse it to use it as a JS array: `data = JSON.parse(data);`, now `data` will be an array, and `data.length` will give you the length of that array, `data[0].title` will give you the title value of the first object in that array etc... `data.length` was 27118 before, because the string consisted of 27118 characters :) – Elias Van Ootegem Jan 05 '15 at 13:44
  • now I got it. But why sometime I don't need to parse the json? this is my first time using JSON.parse. Hmm.. – jamie eason Jan 05 '15 at 13:48
  • 1
    @jamieeason: That depends: if you just `echo` the json encoded string (without quotes) in your output (a php echo in a HTML/JS source file), then you don't need to parse it. If you're using jQuery, and the `Content-type: application/json` header is sent, jQ will parse it for you. If the string is quoted, or is sent as an ajax response with a `Content-Type: text/plain` header, then you have to parse the string first. Sorry for asking this, but I feel like I've done my best helping you out, would you mind awfully upvoting my answer to reward me for my efforts? :-P – Elias Van Ootegem Jan 05 '15 at 13:55
  • if possible I want to upvote every single of your comment, you helped me alot Elias! thanks so much to u! – jamie eason Jan 05 '15 at 14:14
  • @jamieeason: you're welcome... no need to go vote-crazy, though... just that one up-vote on my answer was more than enough. Thanks :D – Elias Van Ootegem Jan 05 '15 at 14:29
0

i have a tricky problem.

What i do. I generate from the System Tables of Databases (DEV ,Test Prod setup) information for Tables, Vies trigger … with PHP and compare the results ti see teh differences with JavaScript.

Also I have a Documentation DB for additional business information which was installed only once on TEST DB.

Therfore I need to connect all four environments to get the data.

I use if ($flag === 'i')

 for information DB and

elseif ($flag === 's')  

for system db‘s.

Result is $row_array and $info_array which must be combined and sendet back to Javascript.

$json_response =   array_merge($rinfo, $rsql );    

echo json_encode($json_response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);    

I try this merge in a different positions in the program.

First time in
elseif ($flag === 'i') {

result json:

    [
    {
        "0": "ACT",……….
    } ][ ]        

second time after   }  //ifelse return also 2 arrays

    [{"0":"ACT","1":"Tabelle Akten","2":"hh","3":null,"4":null,"5":"UCC","6":"Y","7":"Reload Data in Test","8":"y","9":"delete all older tha","10":"n","11":" ","12":"y","13":" ","14":"o","15":"y","16":"o","17":"y","18":"y","19":"Diese tabelle speichert die Acten Verweise","20":"Gert Dorn","21":1570254359,"TDESCRIPTION":"n","TTYPE":" ","TREC_ESTIM":"y","TREC_GROWTH":" ","TDOMAIN":"o","TREL_TYPE":"y","TREL_RULES":"o","THOUSEKEEPING":"y","THOUSE_RULES":"y","TCID":"Diese tabelle speichert die Acten Verweise","TCID_RULES":"Gert Dorn","TUSE_UCC":1570254359,"TUSE_DWH":"","TUSE_ODS":"","TUSE_CWF":"","TUSE_IWF":"","TUSE_OWF":"","TUSE_DEP_MANAGER":"","TENTITY_DESCRIPTION":"","TOWNER":""

,"TTIMESTAMP":""**}][{**"0":"ACT","1":"DB2INST1"

,"2":"USERSPACE1","3":null,"4":"2018-11-21 16:43:20.066567","5":"2018-12-07 10:12:10.255759","6":null,"7":"2020-03-26","8":"2018-11-21 16:43:20.343258","9":3,"NAME":"ACT","CREATOR":"DB2INST1","TBSPACE":"USERSPACE1","REMARKS":"","CTIME":"2018-11-21 16:43:20.066567","STATS_TIME":"2018-12-07 10:12:10.255759","STATISTICS_PROFILE":"","LASTUSED":"2020-03-26","ALTER_TIME":"2018-11-21 16:43:20.343258","COLCOUNT":3}]    

The program code and result you can download at

http://dmdg.io/dmdg.zip

Hope you can help Kind regards gert

Willie Cheng
  • 7,679
  • 13
  • 55
  • 68
-1

Did you consider using array_push?

array_push is always preferred than myArray[] = $value

J.Vassallo
  • 2,282
  • 3
  • 15
  • 14
  • 1
    what is the different? preferred? – jamie eason Jan 05 '15 at 12:31
  • 2
    It's not preferred to `$array[]`. In fact, `$array[]` is _Recommended_! Read [the first note in the docs](http://php.net/array_push) _"Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function."_ – Elias Van Ootegem Jan 05 '15 at 12:35
  • 1
    @jamieeason: cf the link to the manual in my comment above: there is no difference, and `array_push` is ***not*** preferred – Elias Van Ootegem Jan 05 '15 at 12:36
  • @EliasVanOotegem so what is my exact problem? I'm scratching head. – jamie eason Jan 05 '15 at 12:38
  • assigning them over and over will just return 1 object but why in the end I got 3 object? – jamie eason Jan 05 '15 at 12:45