【问题标题】:Multi-dimensional array search to preserve parent多维数组搜索以保留父级
【发布时间】:2012-07-04 07:44:13
【问题描述】:

TL;DR

我有这些数据:var_export 和 print_r。

我需要将其缩小为:http://pastebin.com/EqwgpgAP ($data['Stock Information:'][0][0]);

如何实现它? (动态)


我正在使用 vTiger 5.4.0 CRM 并希望实现一个函数,该函数将根据搜索条件返回特定字段信息。

嗯,vTiger 是一个写得很弱的系统,看起来和感觉都很旧,一切都来自数百个具有多个连接的表(这实际上并没有那么糟糕)等等,但工作就是工作。

需要从产品模块的库存信息块中获取usageunit 选择列表。

由于没有getField();这样的功能,我期待将其从Blocks中过滤掉,这实际上也是在收集有关字段的信息。

getBlocks(); 然后调用接近getFields(); 的东西,再调用接近getValues(); 的东西等等。

所以...

$focus = new $currentModule(); // Products
$displayView = getView($focus->mode);
$productsBlocks = getBlocks($currentModule, $displayView, $focus->mode, $focus->column_fields); // in theory, $focus->column_fields should/could be narrowed down to my specific field, but vTiger doesn't work that way

echo "<pre>"; print_r($productsBlocks); echo "</pre>"; // = http://pastebin.com/3iTDUUgw (huge dump)

如您所见,[Stock Information:] 键下的数组实际上来自翻译(yada,yada...),[0][0] 下包含usageunit 的信息。

现在,我试图从那里取出数据 array_filter();,但我设法得到的唯一东西是将 $productsBlocks 剥离为仅包含 [Stock Information:] 和所有数据:

$getUsageUnit = function($value) use (&$getUsageUnit) {
    if(is_array($value)) return array_filter($value, $getUsageUnit);
    
    if($value == 'usageunit') return true;
};
            
$productsUsageUnit = array_filter($productsBlocks, $getUsageUnit);

echo "<pre>"; print_r($productsUsageUnit); echo "</pre>"; // = http://pastebin.com/LU6VRC4h (not that huge of a dump)

而且,我期待的结果是http://pastebin.com/EqwgpgAP,这是我通过print_r($productsUsageUnit['Stock Information:'][0][0]); 手动获得的。


我如何实现这一目标? (动态...)

【问题讨论】:

  • 我怀疑 vTiger 场景中是否有任何专业人士,有时在阅读源代码时,您会开始怀疑,开发人员自己是否知道它们如何协同工作。
  • ;) 这就是许多系统的问题/在什么条件下您决定 ['Stock Information:'][0][0] 是您想要的?
  • 开启:['Stock Information:'][0][0][2] == 'usageunit'。
  • 您能否使用var_export 添加另一个paste 使复制输入数据变得更加容易;)
  • 查看已编辑的 TL;DR 以获取 var_export 链接。

标签: php arrays multidimensional-array filter vtiger


【解决方案1】:
function helper($data, $query) {
  $result = array();

  $search = function ($data, &$stack) use(&$search, $query) {
    foreach ($data as $entry) {
      if (is_array($entry) && $search($entry, $stack) || $entry === $query) {
        $stack[] = $entry;
        return true;
      }
    }

    return false;
  };


  foreach ($data as $sub) {
    $parentStack = array();
    if ($search($sub, $parentStack)) {
      $result[] = $parentStack[sizeof($parentStack) - 2];
    }
  }

  return $result;
}

$node = helper($data, 'usageunit');
print_r($node);

【讨论】:

  • 结果等于我在 Q 中记下的array_filter() 回调函数$getUsageUnit 的结果,导致block 数据(整个'股票信息:')而不是字段数据(只有数组包含值“usageunit”的子数组)。
  • 我明白了,不太确定结果应该有多窄。 (即将更新)
猜你喜欢
  • 2014-11-11
  • 1970-01-01
  • 2016-05-03
  • 2011-07-05
  • 2019-12-09
  • 2011-11-29
  • 2011-06-26
  • 2014-06-27
相关资源
最近更新 更多