2017-10-13 71 views
0

我想從json文件中獲取數據以加載到我的WordPress網站中。我想從我檢索的網站產品的匹配名稱中獲得價格。我需要產品的名稱來匹配我添加到wordpress產品頁面的產品屬性,然後在名稱與我添加的屬性相匹配時獲取價格。下面的代碼部分工作,但由於某種原因,該屬性的調用不起作用。有什麼建議?試圖使用php獲取json數據

$str = file_get_contents('/run_results_apmex.json'); 

// decode JSON 
$json = json_decode($str, true); 

// default value 
$coinPrice = "No results found"; 
$product_attribute = wc_get_product_terms($product->id , 'pa_apmex'); 
// loop the json array 
foreach($json['coin'] as $value){ 
    // check the condition 
    if($value['name'] == trim($product_attribute)){ 
     $coinPrice = $value['price']; // get the price 
     break; // exit the loop 
    } 
} 

echo $coinPrice; 
+0

檢查你JSON是無效的,我想http://jsonlint.com/ – 2017-10-13 22:37:59

+0

JSON是有效的。再次檢查它是爲了確保。 – AaronS

+0

你可以添加一個var_dump($ str);在file_get_contents之後,我想要顯示父母節點以確定,如果不長。 – 2017-10-13 22:52:33

回答

0

我已經取代你的函數調用

$product_attribute = wc_get_product_terms($product->id , 'pa_apmex');

$product_attribute = '2017 Canada 1 oz Gold Maple Leaf BU'; 

,並運行代碼

$str = file_get_contents('run_results_apmex.json'); 

// decode JSON 
$json = json_decode($str, true); 

// default value 
$coinPrice = "No results found"; 
$product_attribute = '2017 Canada 1 oz Gold Maple Leaf BU'; 
// loop the json array 
foreach ($json['coin'] as $value) { 
    // check the condition 
    if ($value['name'] == trim($product_attribute)) { 
     $coinPrice = $value['price']; // get the price 
     break; // exit the loop 
    } 
} 

echo $coinPrice; 

回聲顯示 「1,316.09 $」。所以,json似乎工作正常。我會var_dump wc_get_product_terms($ product-> id,'pa_apmex')並查看它返回的內容。

+0

謝謝您的迴應。我曾嘗試過以及幾種不同的方式,但它不起作用。當我var_dump,我得到「數組(0)」這是非常不尋常的。爲了幫助打開我的選項,我安裝了高級自定義字段,並嘗試使$ product_attribute = the_field('apmex_vendor_name');並確實拉入該字段的值,但它顯示在前端「找不到結果」旁邊。這很奇怪。 – AaronS