Php 如何根据条件提取Yaml的特定部分?
在下面的yaml文本中检索暴露为true的子对象的名称 输入 预期产量 彼得 现行代码 电流输出 凯西 彼得 在上面的输出中,Cathy是不需要的条目。 正确的输出应该是Peter 提前感谢:我没有看到exposed=true子句 您正在遍历数组并搜索name键,如果找到它,则将其推送到数组中。如果exposed==true,则缺少一个额外的参数 只有在逻辑上,您才能获得一个包含所有条目的数组Php 如何根据条件提取Yaml的特定部分?,php,yaml,Php,Yaml,在下面的yaml文本中检索暴露为true的子对象的名称 输入 预期产量 彼得 现行代码 电流输出 凯西 彼得 在上面的输出中,Cathy是不需要的条目。 正确的输出应该是Peter 提前感谢:我没有看到exposed=true子句 您正在遍历数组并搜索name键,如果找到它,则将其推送到数组中。如果exposed==true,则缺少一个额外的参数 只有在逻辑上,您才能获得一个包含所有条目的数组 parent: child1: units: machine: 1
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);
}