WooCommerce:获取与ACF自定义字段

时间:2017-10-17 00:55:00

标签: php json wordpress woocommerce advanced-custom-fields

我正在尝试从此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;

1 个答案:

答案 0 :(得分:2)

所以这里是正确的代码,它将处理两个数组的情况(有或没有“weight”数组):

$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;

此代码经过测试并正常运行

相关问题