2017-10-13 4 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/ –

+0

json이 유효합니다. 그냥 다시 확인해 봤어. – AaronS

+0

var_dump ($ str)를 추가 할 수 있습니까? file_get_contents 후에 부모 노드가 확실하고 오래 걸리지 않을지를 보여주고 싶습니다. –

답변

0

나는

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

와 함수 호출

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

를 교체하고 코드

$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 할 때 "array (0)"을 얻는다. 정말 이상하다. 내 옵션을 열려면 avanced 사용자 정의 필드를 설치하고 $ product_attribute = the_field ('apmex_vendor_name'); 해당 필드의 값을 가져 오지만 프런트 엔드에 "결과가 없습니다"옆에 표시됩니다. 이것은 모두 이상합니다. – AaronS

관련 문제