我有一些用于长随机xml的脚本,当我知道键时,我需要找到值。我试着使用array_walk_recursive --但当我使用它时--我只在使用echo时才取值。当我使用回报时,我只接受真假..。我需要返回一个变量,以便下一次处理。你能帮帮我吗?
class ClassName{
private $array;
private $key ;
public $value;
public $val;
function getKey($key) {
$this->key = $key;
return $key;
}
function getFind($value, $key)
{
static $i = 0;
if ($key === ($this->key)) {
$value = $value[$i];
$i++;
return $value;
}
}
}
$xml_simple = simplexml_load_file('./logs/xml_in1.xml');
$json = json_encode($xml_simple);
$array = json_decode($json, TRUE);
$obj = new ClassName();
$obj_key = 'pracovnik';
$obj->getKey($obj_key);
print_r(array_walk_recursive($array,[$obj,"getFind"]));
print_r( $obj->value);
发布于 2022-03-19 08:29:05
递归的返回值是:
在成功时返回true,在失败时返回false。
作为一个想法,您可能会使用一个数组,当此if子句为真时,您可以在其中添加值:
if ($key === $this->key) {
然后,您可以创建另一个方法来获得结果:
例如
class ClassName
{
private $key;
private $result = [];
function setKey($key) {
$this->key = $key;
}
function find($value, $key) {
if ($key === $this->key) {
$this->result[$key][] = $value;
}
}
function getResult(){
return $this->result;
}
}
$xml_simple = simplexml_load_file('./logs/xml_in1.xml');
$json = json_encode($xml_simple);
$array = json_decode($json, TRUE);
$obj = new ClassName();
$obj->setKey('pracovnik');
array_walk_recursive($array, [$obj, "find"]);
print_r($obj->getResult());
关于您尝试过的代码,请注意:
return $value;
后面有一行将永远不会执行public $val;
和private $array;
getKey
更好地命名为setKey
,因为您只是在设置键https://stackoverflow.com/questions/71534094
复制相似问题