0

I am trying to create a json response using a for loop and a function but I can't seem to get it to work correctly. How would this be done?

PHP

$count = 0;
foreach ($bookings as $booking){
$item = get_users_custom($user,$count);
$item[$count]['booking_id']=$booking->id;
$count++;
}
echo $item;


function get_users_custom($user,$count=0){
$feed[$count]['user_id']=$user->id; 
return $feed;
}
2
  • where is json?? Commented Jun 25, 2017 at 7:00
  • Item is overwritten on each run in the for loop Commented Jun 25, 2017 at 7:04

2 Answers 2

1

PHP json_encode() function converts a PHP value into a JSON value. For example, from a PHP array, it can create a JSON representation of that array.

$count = 0;
foreach ($bookings as $booking){
$item = get_users_custom($user,$count);
$item[$count]['booking_id']=$booking->id;
$count++;
}
echo json_encode($item);


function get_users_custom($user,$count=0){
$feed[$count]['user_id']=$user->id; 
return $feed;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your $item will only hold the last booking. It's overwritten on each booking.
0

You should create a simple php array and the convert it to JSON using json_encode()

https://www.w3schools.com/js/js_json_php.asp

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.