简体   繁体   中英

Trouble passing an array created by foreach into JSON

I am using Stripe to handle client payments and maintain subscriptions (side note, it's amazing). I need to list a customer's subscriptions in my webpage and I need to assume they can have up to 300 subscriptions (basically unlimited). I created some code in PHP that succesfully queries Stripe for a customer's subscriptions but only the the last (in this case the fifth on the test account) subscription is being sent through the JSON.

Here is my PHP code:

$custsubs = \Stripe\Customer::retrieve($customerID)->subscriptions->all(array(
      'limit'=>300));

               $i = 1;

               foreach ($custsubs['data'] as  $row){
                $rows= '<tr></td><td>'.$row['plan']['id'].'</td><td>'.$row['metadata']['Cust_Info'].'</td><td>$'.(($row['plan']['amount'])/100).'</td><td>'.$row['plan']['interval'].'ly</td><td>
                <div style="text-align:right" id="setdefaultplan'.$i.'" name="setdefaultplan'.$i.'"> <button class="button btn-blue" type="button" id="defplan'.$i.'" ><i class="fa fa-level-down"></i> Change </button></div></td><td>
                <div style="text-align:right" name="remplan'.$i.'" id="remplan'.$i.'"> <button class="button btn-red" type="button" id="removeplan'.$i.'" ><i class="fa fa-fw fa-ban"></i> Cancel Plan </button></div></td></tr>';
               $i++;
                               }
               $results = array('error' => false,               
                    'rows' => $rows
                    );
                echo json_encode($results);
                die();

The JSON result looks like:

{"error":false,"rows":"<tr><\/td><td>Monthly DIY Web Portal Access<\/td><td>Test Info<\/td><td>$6.95<\/td><td>monthly<\/td><td>\r\n\t\t\t\t<div style=\"text-align:right\" id=\"setdefaultplan5\" name=\"setdefaultplan5\"> <button class=\"button btn-blue\" type=\"button\" id=\"defplan5\" ><i class=\"fa fa-level-down\"><\/i> Change <\/button><\/div><\/td><td>\r\n\t\t\t\t<div style=\"text-align:right\" name=\"remplan5\" id=\"remplan5\"> <button class=\"button btn-red\" type=\"button\" id=\"removeplan5\" ><i class=\"fa fa-fw fa-ban\"><\/i> Cancel Plan <\/button><\/div><\/td><\/tr>"}

I pass res.rows into JQuery to make it neatly render inside an HTML table, but I don't understand why I am only getting the 5th instance in the foreach loop. How do I make it so I get them all sent throw res.rows?

Thanks!

You never store $rows into the array until AFTER the loop completes, so you only ever store the LAST row produced.

You want:

foreach(...) {
   $rows[] = ....;
        ^^---array append
}

instead, so you build an array of rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM