2017-02-13 119 views
0

我很确定我非常接近所以希望快速回答​​。输出JSON数组附加额外元素PHP

我能够生成这个JSON:

apps: [ 
    { 
     0: { 
      PublisherCount: "7" 
    }, 
     Id: "87", 
     AppName: "Productivity, Focus, Habits & Life Success by Audiojoy", 
     AppBundle: "productivitymind" 
    } 
] 

但我试图去:

apps: [ 
    { 
     Id: "87", 
     AppName: "Productivity, Focus, Habits & Life Success by Audiojoy", 
     AppBundle: "productivitymind", 
     PublisherCount: "7" 
    } 
] 

这里是我的输出循环(我认为这个问题是在第5 row其中我array_push PublisherCount的新值。它创建一个附加节点,而不是将其添加到结尾。谢谢。

+0

hum,试试'$ temp_array [$ i] ['PublisherCount'] = fetch_all(get_publisher_count_by_app_id($ row ['Id']))[0] ['PublisherCount'];'(并缩进您的代码) – nicolast

回答

1

你行这样的:

['Id' => "87", 
'AppName' => "Productivity, Focus, Habits & Life Success by Audiojoy", 
'AppBundle' => "productivitymind"] 

fetch_all(get_publisher_count_by_app_id($row['Id']))[0]返回一个这样的数组:

['PublisherCount' => 7] 

所以当你用它追$temp_array[$i][],整个阵列被分配到0密钥$temp_array[$i]

有多种不同的方法可以得到PublisherCount的值。一种方法是使用array_mergeget_publisher_count_by_app_id的结果与$row结合起来,然后将修改后的$row添加到主阵列中。

while ($row = mysqli_fetch_assoc($publisher_apps)) { 
    $count = fetch_all(get_publisher_count_by_app_id($row['Id']))[0]; 
    $temp_array[] = array_merge($row, $count); 
} 

如果你这样做,$i应该成为不必要的。

+0

是! @Dont'恐慌,工作。谢谢。有道理,我不断为它获得一个单独的密钥。 –

0

它改成这样:

$temp_array = array(); 

while ($row = mysqli_fetch_assoc($publisher_apps)) { 
    $row['PublisherCount'] = fetch_all(get_publisher_count_by_app_id($row['Id']))[0]['Pub‌​lisherCount']; 
    $temp_array[] = $row; 
} 

$publisher_apps = $temp_array; 

$result = array("apps"=>$publisher_apps); 

output_json($result); 
+0

this结果在此: 应用:[ { ID: “87”, AppName的: “生产力,专注,习惯和通过Audiojoy生活中取得成功”, 的appbundle: “productivitymind”, }, { PublisherCount:{ PublisherCount:“12” } } ] –

+1

我的不好,我已经更新了我的答案。请改为更新的代码。但是,在获得它的工作之后,出于性能考虑,而不是使用“fetch_all”函数,您应该使用“fetch_one”或“fetch_first”类型的函数(如果存在于代码库中)。 – ablopez