0

I'm trying to create JSON arrays to postback to them to Slack with info from a while loop.

Here is the code I've came up with:

$adset = null;

while ($row = mysqli_fetch_array($leadsAdsetsQuery)) {
  if ($row["adset"] != $adset) {
    $adset = $row["adset"];
    echo "{$adset}<br>";
  }
  echo $row["id"] . "<br>";
}

The output is:

Adset Name 1
20
Adset Name 2
34
Adset Name 3
11

And I need to have a new JSON array for each Adset Name with the number of leads structure like this:

  'attachments' => 
  array (
    0 => 
    array (
      'fallback' => 'XXX',
      'text' => 'XXX',
      'fields' => 
      array (  
        0 => 
        array (
          'title' => 'Adset Name 1',
          'value' => '20',
          'short' => true,
        ),
        1 => 
        array (
          'title' => 'Adset Name 2',
          'value' => '34',
          'short' => true,
        ),
        2 => 
        array (
          'title' => 'Adset Name 3',
          'value' => '11',
          'short' => true,
        ),
      ),
      'color' => '#F35A00',
    ),
  )

I'm not a big expert in JSON nor in PHP and google didn't seem to help.

1
  • 1
    Don't try to build a JSON string. Just build a PHP array, then convert it to JSON before posting. Commented May 30, 2017 at 19:33

1 Answer 1

2
<?php
   $arrResult = array();
   $arrResult['attachments'] = array();

   // add 0 'fallback'  'text'  'fields  'color'
   $arrResult['attachments'][0] = array(
      'fallback' => 'XXX',
      'text' => 'XXX',
      'fields' => array(),
      'color' => '#F35A00'
   );

   // add 0 'fields'
   while($row = mysqli_fetch_array($leadsAdsetsQuery)){
      if(!empty($row['adset']) and !empty($row['id'])){
         $arrResult['attachments'][0]['fields'][] = array(
            'title' => $row["adset"],
            'value' => $row['id'],
            'short' => true
         );
      };
   };

   // print JSON 
   echo json_encode($arrResult, JSON_FORCE_OBJECT);
?>
Sign up to request clarification or add additional context in comments.

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.