如果数据名称与php匹配产品属性,则尝试获取json数据

时间:2017-10-12 20:14:29

标签: javascript php json wordpress woocommerce

        我试图从json文件中获取数据以加载到我的wordpress网站。我想从我抓取的网站产品的匹配名称中获取价格。我需要产品的名称以匹配我在wordpress上添加到产品页面的产品属性,然后在名称与我添加的属性匹配时获取价格。我不知道我是否有意义,但到目前为止这是我的代码。它部分工作,但它在我的所有产品上都做了相同的价格。我是php的新手,所以有人可以协助吗?

    <?php

$str = file_get_contents('/run_results_apmex.json');

// decode JSON
$json = json_decode($str, true);

// get the data
$coinPrice = $json['coin'][1]['price'];

// echo it
if($json['name'] == $product->get_attribute[ 'Apmex Vendor Name' ]){
echo $coinPrice;
}
else{
echo 'No results found';
}

?>

1 个答案:

答案 0 :(得分:0)

您需要循环json数组以检查product属性并获得价格。

$str = file_get_contents('/run_results_apmex.json');

// decode JSON
$json = json_decode($str, true);

// default value
$coinPrice = "No results found";
$product_attribute = '1 oz Gold American Eagle BU (Random Year)';
// loop the json array
foreach($json['coin'] as $value){
    // check the condition
    if($value['name'] == trim($product_attribute)){ 
        $coinPrice = $value['price']; // get the price 
        break; // exit the loop
    }
}

echo $coinPrice;

或者你可以创建一个递归函数来检查in_array

$str = file_get_contents('http://gold.explorethatstore.com/wp-content/themes/divi-ETS-child-theme/run_results_apmex.json');

// decode JSON
$json = json_decode($str, true);

// here I am passing the string instead of $product->get_attribute[ 'Apmex Vendor Name' ]. replace it in your code
$product_attribute = '1 oz Gold American Eagle BU (Random Year)';
$coinPrice = ($check = in_array_recursive(trim($product_attribute), $json['coin'])) ? $check['price']: 'No results found';
echo $coinPrice;
// output is $1,426.19

function in_array_recursive($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_recursive($needle, $item, $strict))) {
            return $item;
        }
    }
    return false;
}