Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
Y
yii2
Project
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
PSDI Army
yii2
Commits
c4d11c6a
Commit
c4d11c6a
authored
Apr 11, 2012
by
Qiang Xue
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Added ArrayHelper::index().
parent
1b6c24fe
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
49 additions
and
0 deletions
+49
-0
ArrayHelper.php
framework/util/ArrayHelper.php
+49
-0
No files found.
framework/util/ArrayHelper.php
View file @
c4d11c6a
...
@@ -69,4 +69,52 @@ class ArrayHelper extends \yii\base\Component
...
@@ -69,4 +69,52 @@ class ArrayHelper extends \yii\base\Component
{
{
return
isset
(
$array
[
$key
])
||
array_key_exists
(
$key
,
$array
)
?
$array
[
$key
]
:
$default
;
return
isset
(
$array
[
$key
])
||
array_key_exists
(
$key
,
$array
)
?
$array
[
$key
]
:
$default
;
}
}
/**
* Converts an array such that it is indexed by the specified column values or anonymous function results.
* This method should be used only for two or higher dimensional arrays.
* For example,
*
* ~~~
* $array = array(
* array('id' => '123', 'data' => 'abc'),
* array('id' => '345', 'data' => 'def'),
* );
* $result = ArrayHelper::index($array, 'id');
* // the result is:
* // array(
* // '123' => array('id' => '123', 'data' => 'abc'),
* // '345' => array('id' => '123', 'data' => 'abc'),
* // )
*
* // using anonymous function
* $result = ArrayHelper::index($array, function(element) {
* return $element['id'];
* });
*
* Note that if an index value is null, it will NOT be added to the resulting array.
*
* @param array $array the multidimensional array that needs to be indexed
* @param mixed $key the column name or anonymous function whose result will be used to index the array
* @return array the indexed array (the input array will be kept intact.)
*/
public
static
function
index
(
$array
,
$key
)
{
$result
=
array
();
if
(
$key
instanceof
\Closure
)
{
foreach
(
$array
as
$element
)
{
$key
=
call_user_func
(
$key
,
$element
);
if
(
$key
!==
null
)
{
$result
[
$key
]
=
$element
;
}
}
}
else
{
foreach
(
$array
as
$element
)
{
if
(
isset
(
$element
[
$key
])
&&
$element
[
$key
]
!==
null
)
{
$result
[
$element
[
$key
]]
=
$element
;
}
}
}
return
$result
;
}
}
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment