php在多维数组中根据键名快速查询其父键以及父键值的代码
有一个多维数组,有多少维大家可以自定义。假如我们要在这个数组中找一个键为'subIndex'的值,我们可以用for、foreach等方法遍历查找 反过来,假如我们任意给出一个或多个键,要求找出这个键的父级数组的键和值。这又如何实现?
我这么想的:
遍历一遍多维数组,将所有的键建立索引生成一个一维数组;
每次通过键名去查这个键的上级数组及数据
OK,代码如下
indexKey创建索引数组函数:
代码如下:
/**
* FILE_NAME : arr.php FILE_PATH : test/
* 在多维数组中根据键名快速查询其父键以及父键值
*
* @copyright Copyright (c) 2006-2010 mail:levi@cgfeel.com
* @author Levi
* @package test.arr
* @subpackage
* @version 2011-04-29
*/
header("Content-Type: text/html; charset=utf-8");
$arr = array
(
'china' => array
(
'name' => '中国',
'cite' => array
(
'beijing' => array
(
'name' => '北京',
'site' => array('chaoyang' => '朝阳区', 'xuanwu' => '宣武区')
),
'shanghai' => array
(
'name' => '上海',
'site' => array('jingan' => '静安区', 'huangpu' => '黄浦区')
)
)
)
);
function printA($data)
{
echo '
'; <br>print_r($data); <br>echo '
}
function indexKey($data, $parent = NULL)
{
$arr = array();
foreach ($data as $key => $value)
{
$arr[$key] = $parent;
if (is_array($value))
{
$arr += indexKey($value, $key);
}
}
return (Array)$arr;
}
printA(indexKey($arr));
?>
打印出数据如下
Array
(
[china] =>
[name] => china
[cite] => china
[beijing] => cite
[site] => beijing
[chaoyang] => site
[xuanwu] => site
[shanghai] => cite
[jingan] => site
[huangpu] => site
)
不过上面那样写存在一个问题,即:如果有同名键,会造成丢失,于是我写了这么一个类
只需要将数组传递给对象,对象提供两个接口
printArr 打印索引数组
search 查询键名的父数组键名
IndexKey创建查询索引查询类:
代码如下:
/**
* FILE_NAME : arr.php FILE_PATH : test/
* 在多维数组中根据键名快速查询其父键以及父键值
*
* @copyright Copyright (c) 2006-2010 mail:levi@cgfeel.com
* @author Levi
* @package test.arr
* @subpackage
* @version 2011-04-29
*/
header("Content-Type: text/html; charset=utf-8");
$arr = array
(
'china' => array
(
'name' => '中国',
'cite' => array
(
'beijing' => array
(
'name' => '北京',
'site' => array('chaoyang' => '朝阳区', 'xuanwu' => '宣武区')
),
'shanghai' => array
(
'name' => '上海',
'site' => array('jingan' => '静安区', 'huangpu' => '黄浦区')
)
)
)
);
function printA($data)
{
echo '
'; <br>print_r($data); <br>echo '
}
function printP(IndexKey $obj, $key)
{
$parent = $obj->search($key);
if ($parent)
{
echo '"'.$key.'" Parent Key is: ';
if (!is_array($parent))
{
echo $parent."
\n";
}
else printA($parent);
}
else echo 'NO Parent OR No Search of "'.$key.'"!'."
\n";
}
class IndexKey
{
private $_arr = array();
public function __construct($data)
{
$this->_createIndex($data);
}
public function printArr()
{
return (Array)$this->_arr;
}
public function search($key)
{
return isset($this->_arr[$key]) ? $this->_arr[$key] : NULL;
}
private function _createIndex($data, $parent = NULL)
{
foreach ($data as $key => $value)
{
$this->_checkIndex($key, $parent);
if (is_array($value))
{
$this->_createIndex($value, $key);
}
}
}
private function _checkIndex($key, $parent)
{
$index = isset($this->_arr[$key]) ? $this->_arr[$key] : NULL;
if ($index)
{
if (is_array($index))
{
array_push($this->_arr[$key], $parent);
}
else $this->_arr[$key] = array($index, $parent);
}
else $this->_arr[$key] = $parent;
}
}
$index = (Object)new IndexKey($arr);
printA($index->printArr());
printP($index, 'beijing');
printP($index, 'name');
printP($index, 'china');
?>
最后只差一个数据的输出了,于是我将这个类修改了下
提供了三个对外的方法
printArr 打印索引数组
search 查询键名的父数组键名
parentValue 查询父键值
代码如下:
/**
* FILE_NAME : arr.php FILE_PATH : test/
* 在多维数组中根据键名快速查询其父键以及父键值
*
* @copyright Copyright (c) 2006-2010 mail:levi@cgfeel.com
* @author Levi
* @package test.arr
* @subpackage
* @version 2011-04-29
*/
header("Content-Type: text/html; charset=utf-8");
$arr = array
(
'china' => array
(
'name' => '中国',
'cite' => array
(
'beijing' => array
(
'name' => '北京',
'site' => array('chaoyang' => '朝阳区', 'xuanwu' => '宣武区')
),
'shanghai' => array
(
'name' => '上海',
'site' => array('jingan' => '静安区', 'huangpu' => '黄浦区')
)
)
)
);
function printA($data)
{
echo '
'; <br>print_r($data); <br>echo '
}
function printP2(IndexArr $obj, $key)
{
$parent = $obj->search($key);
if (!is_array($parent))
{
if ($parent)
{
echo '"'.$key.'" Parent Key is: '.$parent."
\n";
}
else echo 'NO Parent OR No Search of "'.$key.'"!'."
\n";;
echo '"'.$key.'" Parent "'.$parent.'" Value is: ';
printA($obj->parentValue($key));
}
else printA($parent);
}
class IndexArr
{
private $_arr = array();
public function __construct($data)
{
$this->_createIndex($data);
}
public function printArr()
{
return (Array)$this->_arr;
}
public function search($key)
{
return isset($this->_arr[$key]) ? $this->_arr[$key]['parent'] : NULL;
}
public function parentValue($key)
{
return isset($this->_arr[$key]) ? $this->_arr[$key]['data'] : NULL;
}
private function _createIndex($data, $parent = NULL)
{
foreach ($data as $key => $value)
{
$this->_checkIndex($key, $parent, $data);
if (is_array($value))
{
$this->_createIndex($value, $key);
}
}
}
private function _checkIndex($key, $parent, $data)
{
$data = $parent && isset($data[$parent]) ? $data[$parent] : $data;
!isset($this->_arr[$key]) && $this->_arr[$key] = array('data' => $data, 'parent' => '');
$index = &$this->_arr[$key]['parent'];
if (!empty($index))
{
if (is_array($index))
{
array_push($index, $parent);
}
else $index = array($index, $parent);
}
else $index = $parent;
}
}
$index2 = (Object)new IndexArr($arr);
printA($index2->printArr());
printP2($index2, 'beijing');
printP2($index2, 'name');
printP2($index2, 'china');
?>
源文件代码:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

A matrix is a set of numbers arranged in rows and columns. A matrix with m rows and n columns is called an mXn matrix, and m and n are called its dimensions. A matrix is a two-dimensional array created in Python using lists or NumPy arrays. In general, matrix multiplication can be done by multiplying the rows of the first matrix by the columns of the second matrix. Here, the number of columns of the first matrix should be equal to the number of rows of the second matrix. Input and output scenario Suppose we have two matrices A and B. The dimensions of these two matrices are 2X3 and 3X2 respectively. The resulting matrix after multiplication will have 2 rows and 1 column. [b1,b2][a1,a2,a3]*[b3,b4]=[a1*b1+a2*b2+a3*a3][a4,a5,a6][b5,b6][a4*b2+a

One-dimensional arrays are sorted using the sort() function, two-dimensional arrays are sorted by internal elements using the usort() function, and high-dimensional arrays are sorted by hierarchical elements using the multi-layer nested usort() function. Solving the decomposition problem layer by layer is the key.

How to merge multiple arrays into a multi-dimensional array in PHP In PHP development, we often encounter the need to merge multiple arrays into a multi-dimensional array. This operation is very useful when operating large data collections and can help us better organize and process data. This article will introduce you to several common methods to achieve this operation, and attach code examples for reference. Method 1: Use the array_merge function. The array_merge function is a commonly used array merging function in PHP. It can merge multiple arrays.

Arrays are a very common data type in PHP. Sometimes, we will face situations involving multi-dimensional arrays. In this case, if we need to perform the same operation on all elements, we can use the array_walk_recursive() function. The array_walk_recursive() function is a very powerful recursive function in PHP that can help us perform recursive operations on multi-dimensional arrays. It can recursively traverse each element of a multi-dimensional array and perform corresponding operations on it.

Two effective ways to reverse multidimensional PHP arrays: Recursively using the array_reverse() function: Recursively reverse the elements of each nested array. PHP7's array_reverse() function: Use the new overload of the array_reverse() function to reverse multi-dimensional arrays.

How to sort multi-dimensional arrays in PHP In PHP, arrays are a very common and important data structure, and multi-dimensional arrays are used more frequently in some complex data processing. However, sorting multidimensional arrays can be tricky. This article will show you how to sort multidimensional arrays in PHP and provide specific code examples. Before we begin, let's first understand the structure of multidimensional arrays. Multidimensional array means that the elements in an array are also an array, forming a nested structure. For example: $st

In-depth discussion of PHP arrays: comprehensive analysis of multi-dimensional arrays, associative arrays, etc. Arrays in PHP are a very important data structure that can store multiple data items and access them through indexes. In PHP, arrays can be divided into different types such as indexed arrays, associative arrays, and multidimensional arrays. Each type has its own unique uses and characteristics. This article will delve into the various types of PHP arrays, including how to declare, access, traverse and operate arrays, and will provide specific code examples to help readers better understand. 1. Index array index number

How to loop through a multidimensional array in PHP In PHP, an array is a powerful data structure that can hold multiple values. Multidimensional arrays are a further extension of arrays and can accommodate multiple arrays. Loop traversal is a common operation method when dealing with multi-dimensional arrays. This article will introduce how to use different loop methods to traverse multi-dimensional arrays in PHP and provide corresponding code examples. Using for loop to traverse multi-dimensional arrays for loop is one of the most common and widely used loop methods. It can nest multiple for loops.
