dottwatson/lonfo

通过访问节点的子节点和父节点来遍历数组

v1.0.2 2020-08-25 08:33 UTC

This package is auto-updated.

Last update: 2024-09-15 01:57:48 UTC


README

通过访问节点的子节点和父节点来遍历数组

安装

在你的项目中

composer require dottwatson/lonfo

使用方法

$data = [
    'bar' => [0,1,2,3,4,5],
    'foo' => [10,20,30,40,50]
];

使用专用函数

$array = lonfo($data); //returns a Lonfo\Walker Object

或使用实例

use Lonfo\Walker;

$array = new Walker($data); //returns a Lonfo\Walker Object

然后遍历你的数组

$item = $array->get('bar'); //returns a Lonfo\Walker Object

$itemData = $array->get('bar')->value(); //returns  [0,1,2,3,4,5]

//retrieve a value and back to its parent

$item = $array->get('bar'); //returns a Lonfo\Walker Object
$parentNode = $item->parent(); //returns a Lonfo\Walker Object of the parent array

//cycle items in array
while($item = $array->next()){
   print_r($item->value());
}

//rewind pointer
$array->rewind();

访问值

$value = $array->get('foo')->get(2);
echo $value->value(); //returns 30

$parent = $value->parent()->value(); // returns  [10,20,30,40,50]


$result = $array
    ->nthChild(2)   //select child #2
    ->append(1000)  //add 1000
    ->parent()      //return top  of proviouse hthChild
    ->set('genders',['Male','Female','Unisex']) //add key=>value
    ->nthChild(1)   //select child #1
    ->set(6,60)     // add key=>value
    ->parent()      // return top of proviouse hthChild
    ->value();       //get value

// result = Array
// (
//     [bar] => Array
//         (
//             [0] => 0
//             [1] => 1
//             [2] => 2
//             [3] => 3
//             [4] => 4
//             [5] => 5
//             [6] => 60
//         )

//     [foo] => Array
//         (
//             [0] => 10
//             [1] => 20
//             [2] => 30
//             [3] => 40
//             [4] => 50
//             [5] => 1000
//         )

//     [genders] => Array
//         (
//             [0] => Male
//             [1] => Female
//             [2] => Unisex
//         )

// )

echo $array->get('bar')->get(2)->xpath(); // returns "bar/2"

echo $array->xfind('gender/0')->value(); //returns "Male"

数组上的可用方法

以下是在 Lonfo\Walker 上可用的方法的列表

值上的可用方法

以下是在 Lonfo\Value 上可用的方法的列表