得到嵌套的json响应

时间:2016-12-10 08:42:25

标签: php json

我有这样的表store_profile

id Storename        Storetype        address
1  Samsung Store    Electronics      Delhi
2  Levi             Clothing         Mumbai
3  Soni             Electronics      Bangalore

和第二个表Offers

id Store_id         offer           price
1  Samsung Store    flat 30% off     20000
2  Levi             Exchange         5000
3  Samsung Store    Exchange offer   40000

我希望获取store_profile针对特定类型的所有商店详细信息,例如 Electronics 以及每个商店的单行优惠,而不是重复,因为我从此语法中获取json mysql查询是: -

SELECT * , Offers.Store_id
FROM Store_profile INNER JOIN
     Offers
     ON Store_profile.Storename = Offers.Store_id AND
        Store_profile.Storetype like '%Electronics%'

这是我的PHP代码

$sql ="SELECT * , Offers.Store_id FROM Store_profile INNER JOIN Offers ON Store_profile.Storename = Offers.Store_id AND Store_profile.Storetype like '%Electronics%' LIMIT 0 , 300 ";
$r = mysqli_query($con,$sql);

$result = array();
while($row = mysqli_fetch_array($r)){
    array_push($result,array(
        'Store_Name'=>$row['Storename'],
        'Store_address'=>$row['address'],
        'Offer_Title'=>$row['offer'],
        'MRP_Price'=>$row['price'],
        )
    );
}
echo json_encode(array('result'=>$result));
mysqli_close($con);

1 个答案:

答案 0 :(得分:0)

  

...我想让json喜欢这个结果[" Storename" -Samsung Store,Store_address - Delhi,Offer [Offer_Title-Flat 30%Off,MRP_Price20000,Offer_Title-Exchange offer,MRP_Price40000]]

按以下方式更改var BASS_Initialized: Boolean; procedure InitializeWizard2(); begin ExtractTemporaryFile('BASS.dll'); ExtractTemporaryFile('CallbackCtrl.dll'); ExtractTemporaryFile('botva2.dll'); ExtractTemporaryFile('MusicButton.png'); ExtractTemporaryFile('Music.mp3'); BASS_Init('{tmp}\Music.mp3') BASS_CreateOnOffButton(WizardForm, '{tmp}\MusicButton.png', 20, 320, 36, 36, 4); BASS_Initialized := True; end; procedure DeinitializeSetup(); begin if BASS_Initialized then begin BASS_DeInit; gdipShutdown; end; end; 循环和后续while()函数调用,

json_encode()

更新

根据您的评论,

  

...我在store_profile中有一个商店,但这个商店在商品表中没有任何商品。我没有在我的json中获得这个商店的数据

您必须使用$result = array(); while($row = mysqli_fetch_array($r)){ if(!isset($result[$row['Store_id']])){ $result[$row['Store_id']] = array('Store_Name'=>$row['Storename'], 'Store_address'=>$row['address']); } $result[$row['Store_id']]['offer'][] = array('Offer_Title'=>$row['offer'],'MRP_Price'=>$row['price']); } echo json_encode(array('result' => array_values($result))); 来包含结果集中LEFT JOIN表中的所有匹配的行。此外,您需要在加入条件后使用Store_profile而不是WHERE。所以你的查询应该是这样的:

AND

随后,按以下方式更改SELECT * , Offers.Store_id FROM Store_profile LEFT JOIN Offers ON Store_profile.Storename = Offers.Store_id WHERE Store_profile.Storetype LIKE '%Electronics%' LIMIT 0 , 300 循环和while()函数调用,

json_encode()