【问题标题】:Only grab a value from an api result when a condition is met仅在满足条件时从 api 结果中获取值
【发布时间】:2020-12-02 09:08:58
【问题描述】:

在我运行的项目中,我试图以最低的价格获取产品。 但产品可以是新的或翻新的。我只想选择新产品的价格。最初我抓住了它们,并有以下代码(有效)

$price = min(array_column($product_array['products'][0]['offerData']['offers'],'price'));

显示它是新的还是翻新的字段位于:

['products'][0]['offerData']['offers']['condition']

有没有办法获得具有“条件”“新”的产品的最低价格?

【问题讨论】:

  • $product_array['products'][0]['offerData']['offers'] 上使用array_filter。或者使用简单的foreach 循环。

标签: php arrays api


【解决方案1】:

在 cmets 中有点回答,但要给出答案:

// make it shorter
$offers = $product_array['products'][0]['offerData']['offers'];

// filter out all but new condition
$new = array_filter($offers, function($v) { return $v['condition'] == 'new'; });

// get prices and the minimum
$price = min(array_column($new, 'price'));

可以在一行中完成:

$price = min(array_column(
             array_filter($product_array['products'][0]['offerData']['offers'],
                          function($v) {
                              return $v['condition'] == 'new';
                          }), 'price'));

另外,在 让它更短 部分中,如果你从某些东西(即 JSON)中获取这个数组,那么在那里缩短它(除非你需要全部):

$offers = json_decode($_POST['whatever'], true)['products'][0]['offerData']['offers'];

【讨论】:

  • 非常感谢,谢谢。我对这些东西真的很陌生,所以这既帮助我完成它,也帮助我理解它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多