0

I want to know how to add dynamic key/value pair in an Json array of objects during execution.

$result2 is from database query results

while( $row = mysql_fetch_assoc($result2) )
{
 $result_show[]=$row;
 $result_show[]['ismy']='1';
 $result_show[]['time']='close';
 $result_show[]['img']  = $path;
}

My Result is:

{"results":[{"id":"412"},{"ismy":"0"},{"time":"close"},{"img":"1.JPG"}]}

Desired Result is:

{"results":[{"id":"412","ismy":"0","time":"close","img":"1.JPG"}]}

Whats wrong with this? Please help me out.

1
  • yes got the answer and desired output. Commented Mar 16, 2016 at 4:48

2 Answers 2

2

Use this code :-

<?php
$i = 0;
while( $row = mysql_fetch_assoc($result2) ) {
{
    $result_show[$i]=$row;
    $result_show[$i]['ismy']='1';
    $result_show[$i]['time']='close';
    $result_show[$i]['img']  = $path;
     $i++;
}
?>
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is the you are using the shortened version of the array_push function four times. What you really want to do is add one single element to the results array, try it with:

while( $row = mysql_fetch_assoc($result2) ) {
  $row['ismy']   = '1';
  $row['time']   = 'close';
  $row['img']    = $path;
  $result_show[] = $row;
}

Comments

Your Answer

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.