【问题标题】:How to extract specific part of Yaml depending on a condition?如何根据条件提取 Yaml 的特定部分?
【发布时间】:2011-12-15 08:00:52
【问题描述】:

在以下 yaml 文本中检索子项的名称​​其中暴露为真

输入

parent:
  child1:
    units:
        machine: 1
        name: Cathy
        relation: daughter
        boolean: true
  child2:
    exposed: true
    units:
        machine: 2
        name: Peter
        relation: son
        boolean: false

预期输出

彼得

当前代码

//input
$yaml = <<<EOD
parent:
  child1:
    units:
        name: Cathy
        relation: daughter
  child2:
    exposed: true
    units:
        name: Peter
        relation: son
EOD;

//convert to array
$parsed = yaml_parse($yaml);

//get all values from specific key in a multidimensional array
var_dump(array_value_recursive('name', $parsed));


/**
 * Get all values from specific key in a multidimensional array
 *
 * @param $key string
 * @param $arr array
 * @return null|string|array
 */
function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}

电流输出

凯茜 彼得

在上面的输出中,Cathy 是不需要的条目。 正确的输出应该是 Peter。

提前致谢:)

【问题讨论】:

    标签: php yaml


    【解决方案1】:

    好吧,我在任何地方都看不到exposed=true 子句。

    您正在遍历数组并搜索 name 键,如果找到,则将其推送到数组中。你错过了一个额外的if (exposed == true)..

    你会得到一个包含所有条目的数组是合乎逻辑的。

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多