2 回答

TA貢獻1859條經驗 獲得超6個贊
可能有一百萬種方法可以做到這一點,但最終您將需要一些能夠過濾值和該值的路徑的遞歸方法。為此,以下是這百萬種方法中的一種。
它使用預定義的迭代器:
回調過濾器迭代器
遞歸迭代器迭代器
遞歸數組迭代器
與自定義PathAsKeyDecorator
迭代器結合使用。
<?php
declare(strict_types=1);
final class PathAsKeyDecorator implements \Iterator
{
? ? private RecursiveIteratorIterator $inner;
? ? public function __construct(RecursiveIteratorIterator $inner)
? ? {
? ? ? ? $this->inner = $inner;
? ? }
? ? public function current()
? ? {
? ? ? ? return $this->inner->current();
? ? }
? ? public function next(): void
? ? {
? ? ? ? $this->inner->next();
? ? }
? ? public function key()
? ? {
? ? ? ? $path = [];
? ? ? ? for ($i = 0, $depth = $this->inner->getDepth(); $i <= $depth; $i++) {
? ? ? ? ? ? $path[] = $this->inner->getSubIterator($i)->key();
? ? ? ? }
? ? ? ? return $path;
? ? }
? ? public function valid(): bool
? ? {
? ? ? ? return $this->inner->valid();
? ? }
? ? public function rewind(): void
? ? {
? ? ? ? $this->inner->rewind();
? ? }
}
$input = [
? ? 'steve'? => [
? ? ? ? 'id' => [
? ? ? ? ? ? '#text' => 1,
? ? ? ? ],
? ? ],
? ? 'albert' => [
? ? ? ? 'id' => [
? ? ? ? ? ? '#text' => 2,
? ? ? ? ],
? ? ],
? ? 'john'? ?=> [
? ? ? ? 'profil' => [
? ? ? ? ? ? 'id' => [
? ? ? ? ? ? ? ? '#text' => 3,
? ? ? ? ? ? ],
? ? ? ? ],
? ? ],
];
// this is the filter function that should be customized given your requirements
// or create a factory function which produces these types of filter functions
$filter = static function ($current, array $path): bool {
? ? // with help from the PathAsKeyDecorator
? ? // we can decide on the path to the current value
? ? return ['id', '#text'] === array_slice($path, -2)
? ? ? ? // and the current value
? ? ? ? && 2 === $current;
};
// configure the iterator
$it = new CallbackFilterIterator(
? ? new PathAsKeyDecorator(new RecursiveIteratorIterator(new RecursiveArrayIterator($input))),
? ? $filter,
);
// traverse the iterator
foreach ($it as $path => $val) {
? ? print_r([
? ? ? ? 'path' => $path,
? ? ? ? 'val'? => $val
? ? ]);
}

TA貢獻1799條經驗 獲得超9個贊
完整編輯陣列結構變化的原因。json_encode 用于將數組更改為字符串。僅當每個數組切片中有一個 id 和一個偽值時,它才起作用。
$data = [
'steve' => [
'id' => [
'#text' => 1,
],
'pseudo' => [
'#text' => 'LOL'
],
],
'albert' => [
'id' => [
'#text' => 2,
],
'pseudo' => [
'#text' => 'KILLER'
],
],
'john' => [
'id' => [
'#text' => 3,
],
'pseudo' => [
'#text' => 'NOOBS'
],
],
];
$data = json_encode($data, JSON_NUMERIC_CHECK);
preg_match_all('~"id":{"#text":([^{]*)}~i', $data, $ids);
preg_match_all('~"pseudo":{"#text":"([^{]*)"}~i', $data, $pseudos);
$lnCounter = 0;
$laResult = array();
foreach($ids[1] as $lnId) {
$laResult[$lnId] = $pseudos[1][$lnCounter];
$lnCounter++;
}
echo $laResult[2];
- 2 回答
- 0 關注
- 117 瀏覽
添加回答
舉報