【问题标题】:WooCommerce: Get Json data in multi-dimensional array matching ACF custom fieldWooCommerce:在匹配 ACF 自定义字段的多维数组中获取 Json 数据
【发布时间】:2018-03-28 14:27:48
【问题描述】:

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

【问题讨论】:

  • 有时会出现问题,例如类别名称“Gold American Eagles”有一个“权重”数组,但“Gold American Buffalos”没有权重数组(1 个多级数组少)......所以这是一个问题。所有类别名称应具有相同的结构...
  • 嗯嗯嗯就是这样在网站上爬的,有的结果会回来,有的分类就没有了。 PHP 不会按名称识别数组?

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


【解决方案1】:

所以这是处理两种数组情况的正确代码(有或没有“权重”数组):

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

此代码已经过测试并且可以工作

【讨论】:

  • 谢谢你,工作完美。如果“array_key_exists”有道理,我明白你做了什么。非常感谢您的帮助。你今天为我解决了很多问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2019-04-17
  • 2019-03-28
  • 2023-03-22
  • 2022-11-07
  • 1970-01-01
相关资源
最近更新 更多