0

I'm using this code to generate JSON string, but a faced with one problem, I try to find out is this the last element or not, I am using this if(end($aData) != $aD) but this is comparing the value, there is a problem, when in the array are same values, How could I compare the $keys(get the last key and compare with the current key), or get the last element.

$ret = '['; foreach($aDatas as $aData) { $ret .= "{"; foreach($aData as $key=>$aD) { $ret .= '"'.$key.'":"'.$aD.'"'; if(end($aData) != $aD) $ret .= ','; } $ret .= "}"; if(end($aDatas) != $aData) $ret .= ','; } echo $ret.']'; 
3
  • 2
    This doesn't look like it does anything special. Why don't you use the native json_encode? Commented Mar 24, 2011 at 11:30
  • 1
    why not use json_encode()? php.net/json-encode ? Commented Mar 24, 2011 at 11:31
  • 1
    because I didn't know this function, but now I know, thanks. Commented Mar 24, 2011 at 12:01

3 Answers 3

7

May I suggest this PHP built-in function json_encode()?

Might save you a lot of time.

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

Comments

3

One option would be to use the key() function:

end($aData); if(key($aData) != $key) 

3 Comments

end() will move the array's internal pointer. Besides, array_merge(array(1,2,1), array('foo','bar','quux')).
I had tried, but I got the following error: key() expects parameter 1 to be array, string given in
That would return the key of the last value of $aData or throw an error if that array element is no array.
1

You know the size of the array. So simply increase a counter in every loop and then check if it's the last element.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.