2017-10-17 101 views
1

我試圖從這個json文件中獲取數據,但我需要匹配高級自定義字段的數據。WooCommerce:獲取多維數組中匹配ACF自定義字段的Json數據

$str = file_get_contents('http://gold.explorethatstore.com/wp-content/themes/divi-ETS-child-theme/run_results_bgasc.json'); 

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

// default value 
$coinPrice = "Not Available"; 
$vendorName = get_field('bgasc_vendor_name'); 
// loop the json array 
foreach($json['coin'] as $value){ 
     // check the condition 
     if($value['coin_name'] == $vendorName){ 
       $coinPrice = $value['url']; // get the price 
       break; // exit the loop 
     } 
} 

echo $coinPrice; 
+0

有一個問題,有些時候,例如類別名稱「Gold American Eagles」有一個「重量」數組,但「Gold American Buffalos」沒有重量數組(1個多級數組少)...所以這是一個問題。所有類別名稱應該具有相同的結構... – LoicTheAztec

+0

嗯,這是它在網站上爬行的方式,一些結果會回來,有些類別不會有。 PHP不會按名稱標識數組? – AaronS

+0

我的歉意!這裏是:http://gold.explorethatstore.com/wp-content/themes/divi-ETS-child-theme/run_results_bgasc_gold.json – AaronS

回答

2

因此,這裏是正確的代碼,將處理這兩種陣列的情況下(有或無「權重」排列):

$str = file_get_contents('http://gold.explorethatstore.com/wp-content/themes/divi-ETS-child-theme/run_results_bgasc_gold.json'); 

// Set te Data in a multi-dimensional array 
$json = json_decode($str, true); 

// Default variable values 
$coin_price = "Not Available"; 
$url = ''; 
$break = false; 

// Get the vendor name (like the "coin_name" value) 
$vendorName = get_field('bgasc_vendor_name'); 


// Go through multi-dimensional array with multiple loops 
foreach ($json['categories'] as $category){ 
    // Case with "weight" additional array 
    if(array_key_exists ('weight' , $category)){ 
     foreach ($category['weight'] as $weight){ 
      foreach ($weight['coin'] as $coin){ 
       // check the condition 
       if($coin['coin_name'] == $vendor_name){ 
        $coin_price = $coin['price']; // get the price 
        $url = $coin['url']; // get the url 
        $break = true; // (exit other loops) 
        break; // exit the loop 
       } 
      } 
      if($break) break; // exit the loop 
     } 
     if($break) break; // exit the loop 
    } else { // Case without "weight" additional array 
     foreach ($category['coin'] as $coin){ 
      // check the condition 
      if($coin['coin_name'] == $vendor_name){ 
       $coin_price = $coin['price']; // get the price 
       $url = $coin['url']; // Get the url 
       $break = true; // (exit other loops) 
       break; // exit the loop 
      } 
     } 
     if($break) break; // exit the loop 
    } 
} 

// output price 
echo $coin_price; 

// output URL 
echo $url; 

該代碼測試和工程

+1

謝謝你,工作完美。我明白你做了什麼,如果「array_key_exists」這是有道理的。非常感謝您的幫助。你今天爲我解決了很多問題。 – AaronS