WooCommerce: Get Json data in multi-dimensional array matching ACF custom field

坚强是说给别人听的谎言 提交于 2019-12-11 07:44:24

问题


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;

回答1:


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



来源:https://stackoverflow.com/questions/46780953/woocommerce-get-json-data-in-multi-dimensional-array-matching-acf-custom-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!