3 回答

TA貢獻1784條經驗 獲得超8個贊
您的 JSON 數據:
$jsonData = '{
"dataFlags": 8192,
"totalItemsCount": 6,
"indexFrom": 0,
"indexTo": 0,
"items": [{
"rep": {
"1": {
"id": 1,
"n": "volvo",
"ct": "avl_unit_group",
"c": 54071
},......
}},
{"rep": {
"1": {
"id": 1,
"n": "tesla",
"ct": "avl_unit",
"c": 24132
},..........
},
"repmax": 0
}]}';
試試下面的代碼。它正在工作。我使用 2foreach 將您的 JSON 數據存儲在數據庫中。
$jsonData = json_decode($jsonData,true);
foreach($jsonData['items'] as $items){
foreach($items['rep'] as $rep){
$sql = "INSERT INTO MyGuests (id, n, ct) VALUES (".$rep['id'].",".$rep['n'].",".$rep['ct'].")";
$conn->query($sql)
}
}
獲取每個“rep”及其“id”的結果:
$jsonData = json_decode($jsonData,true);
$allRep = [];
foreach($jsonData['items'] as $items){
$tmpRep = [];
foreach($items['rep'] as $key => $rep){
$tmpRep [] = $key;
}
$allRep[] = implode(', ',$tmpRep);
}
echo "<pre>";
print_r($allRep);
輸出:
Array
(
[0] => 1, 2, 4, 5
[1] => 1, 2
)

TA貢獻1802條經驗 獲得超5個贊
這段代碼是用 php 編寫的。
$rep1="";
foreach ($row['item'] as $key => $value) {
$rep1 .=$value->id.'-';
}
$rep1=substr($rep1, 0, -1);
輸出將是 $rep1= 1-2-4-5

TA貢獻1844條經驗 獲得超8個贊
檢查這個:
$arr = json_decode($yourJSONstring);
foreach($arr->items as $index=>$rep){
foreach($rep->rep as $element){
$reps[$index][] = $element->id;
}
}
代表數組將如下所示:
Array (
[0] => Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 )
[1] => Array ( [0] => 1 [1] => 2 )
)
因此,您可以根據需要輕松將其轉換為字符串格式。
- 3 回答
- 0 關注
- 310 瀏覽
添加回答
舉報