2017-05-30 132 views
0

我试图创建JSON数组以将它们回发给Slack,并使用while循环的信息。PHP while while循环到JSON数组中

这里是我想出了代码:

$adset = null; 

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

输出是:

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

,我需要有一个新的JSON阵列每个Adset名称与数量导致结构是这样的:

'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', 
    ), 
) 

我不是JSON也不在PHP和谷歌似乎并没有帮助大专家。

+1

不要尝试构建JSON字符串。只需构建一个PHP数组,然后在发布之前将其转换为JSON。 – Pickle

回答

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); 
?>