2016-11-10 71 views
0

我試圖在預定義的JSON末尾附加新數據。 我想追加新的數據作爲現有的JSON的一個元素。我的意思是數據被附加爲json的新元素。在php的末尾添加新數據在php中

$jsonData = array(); 
if (!empty($json_mainQuot)) { 
    $jsonData['mainQuot'] = $json_mainQuot; 
} 
if (!empty($json_quotation_hotel)) { 
    $jsonData['quotation_hotel'] = $json_quotation_hotel; 
} 
$tempArray[] = json_decode($state_current_arr[0]['user_date']); 
array_push($tempArray, $jsonData); 
$jsonData_merged = json_encode($tempArray); 

它看起來像這樣

[{ 
    "id": "77", 
    "agent_id": "30524", 
    "raised_by": "C", 
    "from_date": "2016-11-09", 
    "to_date": "2016-11-10", 
    "num_of_days": "1", 
    "num_of_country": "1", 
    "LeadConsultant": { 
     "user_id": "3045", 
     "lead_id": "77" 
    }, 
    "LeadDestination": [{ 
     "from_date": "2016-11-09", 
     "to_date": "2016-11-10", 
     "country_id": "IN", 
     "city_id": "67457", 
     "notes": "", 
     "is_hotel": "1", 
     "is_sight": "1", 
     "is_transfer": "1", 
     "lead_id": "77" 
    }] 
}, { 
    "mainQuot": { 
     "supplier_markup": "0", 
     "lead_destination_id": "168", 
     "user_id": "1", 
     "quot_via": 0 
    }, 
    "quotation_hotel": { 
     "lead_quot_id": "36", 
     "hotel_id": "578917", 
     "giata_id": "531264", 
     "ratings": "3", 
     "address": "Opposite ST Stand,Alibag 402201", 
     "notes": "testing" 
    } 
}] 

,但我想這樣

[{ 
    "id": "77", 
    "agent_id": "30524", 
    "raised_by": "C", 
    "from_date": "2016-11-09", 
    "to_date": "2016-11-10", 
    "LeadConsultant": { 
     "user_id": "3045", 
     "lead_id": "77" 
    }, 
    "mainQuot": { 
     "supplier_markup": "0", 
     "lead_destination_id": "168", 
     "user_id": "1", 
     "quot_via": 0 
    }, 
    "quotation_hotel": { 
     "lead_quot_id": "36", 
     "hotel_id": "578917", 
     "giata_id": "531264", 
     "ratings": "3", 
     "address": "Opposite ST Stand,Alibag 402201", 
     "notes": "testing" 
    }, 
    "LeadDestination": [{ 
     "from_date": "2016-11-09", 
     "to_date": "2016-11-10", 
     "country_id": "IN", 
     "city_id": "67457", 
     "notes": "", 
     "is_hotel": "1", 
     "is_sight": "1", 
     "is_transfer": "1", 
     "lead_id": "77" 
    }] 
}] 
+1

如果你檢查你想要什麼一個json驗證器,你會看到你想要的不是一個有效的json。 –

+0

其實,你得到的不是一個有效的json或 –

+0

現在看到它是有效的json –

回答

1

你需要array_merge代替array_push:

<?php 

$state_current_arr = '{ "id": "77", "agent_id": "30524", "raised_by": "C", "from_date": "2016-11-09", "to_date": "2016-11-10", "LeadConsultant": { "user_id": "3045", "lead_id": "77" }, "LeadDestination": [ { "from_date": "2016-11-09", "to_date": "2016-11-10", "country_id": "IN", "city_id": "67457", "notes": ""}]}'; 

$jsonData = array(); 

    $jsonData['mainQuot'] = 'test'; 
    $jsonData['quotation_hotel'] = 'test'; 

$tempArray = json_decode($state_current_arr,true); 
$tempArray = array_merge($tempArray, $jsonData); 
$jsonData_merged = json_encode($tempArray); 

echo $jsonData_merged; 
+0

謝謝你,你救了我的一天! –