WooCommerce:在与ACF自定义字段匹配的多维数组中获取Json数据 [英] WooCommerce: Get Json data in multi-dimensional array matching ACF custom field

查看:106
本文介绍了WooCommerce:在与ACF自定义字段匹配的多维数组中获取Json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此json文件中获取数据,但是我需要与我设置的高级自定义字段匹配的数据。

I am trying to get data from this json file, but I need the data that matches the advanced custom field I setup.

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


推荐答案

这是处理两个数组的正确代码例(有或没有权重数组):

So here is the correct code that will handle both array cases (with or without "weight" array):

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

此代码已经过测试并且有效

This code is tested and works

这篇关于WooCommerce:在与ACF自定义字段匹配的多维数组中获取Json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆