2017-10-17 102 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