如何筛选数组中update_date大于指定值的selling字段元素
解决PHP数组筛选符合条件的selling元素问题
没问题,这其实很容易解决~ 你需要先筛选出符合update_date条件的对象,再提取对应的selling值,分两步走就好,给你两种常用的实现方式:
方法一:用array_filter + array_column(简洁写法)
先通过array_filter把原数组里update_date大于1522271876的对象挑出来,再用array_column提取selling字段:
// 假设你的原数组是$results $filteredItems = array_filter($results, function($obj) { // 这里判断update_date是否满足条件 return $obj->update_date > 1522271876; }); // 提取符合条件的selling值到$datay1 $datay1 = array_column($filteredItems, 'selling');
方法二:用foreach循环(更直观,适合新手调试)
如果觉得闭包有点抽象,用foreach循环逐个检查也很清晰:
$datay1 = []; foreach ($results as $obj) { // 检查当前对象的update_date是否符合要求 if ($obj->update_date > 1522271876) { // 符合条件就把selling值加入数组 $datay1[] = $obj->selling; } }
两种方法都能达到你的需求,选哪种看你习惯~ 如果后续需要对符合条件的对象做更多操作,foreach会更灵活;如果只是单纯筛选+提取,array_filter的写法更简洁。
内容的提问来源于stack exchange,提问作者can
相关产品推荐
相关产品推荐

