[英]Trying to get json data if the data name matches product attribute with php
我正在嘗試從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';
}
?>
您需要循環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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.