クラス yii\helpers\ArrayHelper
継承 | yii\helpers\ArrayHelper » yii\helpers\BaseArrayHelper |
---|---|
利用可能なバージョン | 2.0 |
ソースコード | https://github.com/yiisoft/yii2/blob/master/framework/helpers/ArrayHelper.php |
ArrayHelper は、アプリケーションで使用できる追加の配列機能を提供します。
ArrayHelper の詳細および使用方法については、配列ヘルパーに関するガイド記事を参照してください。
公開メソッド
メソッド詳細
定義元: yii\helpers\BaseArrayHelper::filter()
指定されたルールに従って配列をフィルタリングします。
例
$array = [
'A' => [1, 2],
'B' => [
'C' => 1,
'D' => 2,
],
'E' => 1,
];
$result = \yii\helpers\ArrayHelper::filter($array, ['A']);
// $result will be:
// [
// 'A' => [1, 2],
// ]
$result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
// $result will be:
// [
// 'A' => [1, 2],
// 'B' => ['C' => 1],
// ]
$result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
// $result will be:
// [
// 'B' => ['D' => 2],
// ]
public static array filter ( $array, $filters ) | ||
$array | array |
ソース配列 |
$filters | iterable |
結果から残すか削除する必要のある配列キーを定義するルール。各ルールは次のとおりです。
|
return | array |
フィルタリングされた配列 |
---|
public static function filter($array, $filters)
{
$result = [];
$excludeFilters = [];
foreach ($filters as $filter) {
if (!is_string($filter) && !is_int($filter)) {
continue;
}
if (is_string($filter) && strncmp($filter, '!', 1) === 0) {
$excludeFilters[] = substr($filter, 1);
continue;
}
$nodeValue = $array; //set $array as root node
$keys = explode('.', (string) $filter);
foreach ($keys as $key) {
if (!array_key_exists($key, $nodeValue)) {
continue 2; //Jump to next filter
}
$nodeValue = $nodeValue[$key];
}
//We've found a value now let's insert it
$resultNode = &$result;
foreach ($keys as $key) {
if (!array_key_exists($key, $resultNode)) {
$resultNode[$key] = [];
}
$resultNode = &$resultNode[$key];
}
$resultNode = $nodeValue;
}
foreach ($excludeFilters as $filter) {
$excludeNode = &$result;
$keys = explode('.', (string) $filter);
$numNestedKeys = count($keys) - 1;
foreach ($keys as $i => $key) {
if (!array_key_exists($key, $excludeNode)) {
continue 2; //Jump to next filter
}
if ($i < $numNestedKeys) {
$excludeNode = &$excludeNode[$key];
} else {
unset($excludeNode[$key]);
break;
}
}
}
return $result;
}
定義元: yii\helpers\BaseArrayHelper::getColumn()
配列内の指定された列の値を返します。
入力配列は、多次元またはオブジェクトの配列である必要があります。
例:
$array = [
['id' => '123', 'data' => 'abc'],
['id' => '345', 'data' => 'def'],
];
$result = ArrayHelper::getColumn($array, 'id');
// the result is: ['123', '345']
// using anonymous function
$result = ArrayHelper::getColumn($array, function ($element) {
return $element['id'];
});
public static array getColumn ( $array, $name, $keepKeys = true ) | ||
$array | array | |
$name | integer|string|array|Closure | |
$keepKeys | boolean |
配列キーを維持するかどうか。false の場合、結果の配列には整数で再インデックスが付けられます。 |
return | array |
列の値のリスト |
---|
public static function getColumn($array, $name, $keepKeys = true)
{
$result = [];
if ($keepKeys) {
foreach ($array as $k => $element) {
$result[$k] = static::getValue($element, $name);
}
} else {
foreach ($array as $element) {
$result[] = static::getValue($element, $name);
}
}
return $result;
}
定義元: yii\helpers\BaseArrayHelper::getValue()
指定されたキーまたはプロパティ名を使用して、配列要素またはオブジェクトプロパティの値を取得します。
キーが配列に存在しない場合は、代わりにデフォルト値が返されます。オブジェクトから値を取得する場合は使用されません。
キーは、サブ配列の値や埋め込みオブジェクトのプロパティを取得するために、ドット形式で指定できます。具体的には、キーがx.y.z
の場合、返される値は$array['x']['y']['z']
または$array->x->y->z
($array
がオブジェクトの場合)となります。もし$array['x']
または$array->x
が配列でもオブジェクトでもない場合、デフォルト値が返されます。配列にすでに要素x.y.z
がある場合、サブ配列を辿る代わりにその値が返されることに注意してください。したがって、['x', 'y', 'z']
のようにキー名の配列を指定して行う方が良いでしょう。
以下に使用例を示します。
// working with array
$username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
// working with object
$username = \yii\helpers\ArrayHelper::getValue($user, 'username');
// working with anonymous function
$fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
return $user->firstName . ' ' . $user->lastName;
});
// using dot format to retrieve the property of embedded object
$street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
// using an array of keys to retrieve the value
$value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
public static mixed getValue ( $array, $key, $default = null ) | ||
$array | array|object |
値を取り出す元の配列またはオブジェクト |
$key | string|Closure|array |
配列要素のキー名、キーの配列、またはオブジェクトのプロパティ名、もしくは値を返す匿名関数。匿名関数のシグネチャは、 |
$default | mixed |
指定された配列キーが存在しない場合に返されるデフォルト値。オブジェクトから値を取得する場合は使用されません。 |
return | mixed |
要素が見つかった場合はその値、それ以外の場合はデフォルト値 |
---|
public static function getValue($array, $key, $default = null)
{
if ($key instanceof \Closure) {
return $key($array, $default);
}
if (is_array($key)) {
$lastKey = array_pop($key);
foreach ($key as $keyPart) {
$array = static::getValue($array, $keyPart);
}
$key = $lastKey;
}
if (is_object($array) && property_exists($array, $key)) {
return $array->$key;
}
if (static::keyExists($key, $array)) {
return $array[$key];
}
if ($key && ($pos = strrpos($key, '.')) !== false) {
$array = static::getValue($array, substr($key, 0, $pos), $default);
$key = substr($key, $pos + 1);
}
if (static::keyExists($key, $array)) {
return $array[$key];
}
if (is_object($array)) {
// this is expected to fail if the property does not exist, or __get() is not implemented
// it is not reliably possible to check whether a property is accessible beforehand
try {
return $array->$key;
} catch (\Exception $e) {
if ($array instanceof ArrayAccess) {
return $default;
}
throw $e;
}
}
return $default;
}
定義元: yii\helpers\BaseArrayHelper::htmlDecode()
文字列の配列内の HTML エンティティを対応する文字にデコードします。
デフォルトでは、配列の値のみがデコードされます。値が配列の場合、このメソッドは再帰的にデコードします。文字列の値のみがデコードされます。
参考: https://www.php.net/manual/en/function.htmlspecialchars-decode.php。
public static array htmlDecode ( $data, $valuesOnly = true ) | ||
$data | array |
デコードされるデータ |
$valuesOnly | boolean |
配列の値のみをデコードするかどうか。 |
return | array |
デコードされたデータ |
---|
public static function htmlDecode($data, $valuesOnly = true)
{
$d = [];
foreach ($data as $key => $value) {
if (!$valuesOnly && is_string($key)) {
$key = htmlspecialchars_decode($key, ENT_QUOTES | ENT_SUBSTITUTE);
}
if (is_string($value)) {
$d[$key] = htmlspecialchars_decode($value, ENT_QUOTES | ENT_SUBSTITUTE);
} elseif (is_array($value)) {
$d[$key] = static::htmlDecode($value, $valuesOnly);
} else {
$d[$key] = $value;
}
}
return $d;
}
定義元: yii\helpers\BaseArrayHelper::htmlEncode()
文字列の配列内の特殊文字を HTML エンティティにエンコードします。
デフォルトでは、配列の値のみがエンコードされます。値が配列の場合、このメソッドは再帰的にエンコードします。文字列の値のみがエンコードされます。
参考: https://www.php.net/manual/en/function.htmlspecialchars.php。
public static array htmlEncode ( $data, $valuesOnly = true, $charset = null ) | ||
$data | array |
エンコードされるデータ |
$valuesOnly | boolean |
配列の値のみをエンコードするかどうか。falseの場合、配列のキーと配列の値の両方がエンコードされます。 |
$charset | string|null |
データが使用している文字セット。設定されていない場合、yii\base\Application::$charsetが使用されます。 |
return | array |
エンコードされたデータ |
---|
public static function htmlEncode($data, $valuesOnly = true, $charset = null)
{
if ($charset === null) {
$charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
}
$d = [];
foreach ($data as $key => $value) {
if (!$valuesOnly && is_string($key)) {
$key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
}
if (is_string($value)) {
$d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
} elseif (is_array($value)) {
$d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
} else {
$d[$key] = $value;
}
}
return $d;
}
定義元: yii\helpers\BaseArrayHelper::index()
指定されたキーに従って配列のインデックスを作成したり、グループ化したりします。
入力は多次元配列またはオブジェクトの配列である必要があります。
$keyは、サブ配列のキー名、オブジェクトのプロパティ名、またはキーとして使用される値を返す匿名関数のいずれかです。
$groupsは、指定されたキーに基づいて入力配列を1つ以上のサブ配列にグループ化するために使用されるキーの配列です。
$key
がnull
として指定されている場合、またはキーに対応する要素の値がnull
であり、さらに$groups
が指定されていない場合、要素は破棄されます。
例
$array = [
['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
['id' => '345', 'data' => 'def', 'device' => 'tablet'],
['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
];
$result = ArrayHelper::index($array, 'id');
結果は、キーがid
属性の値である連想配列になります。
[
'123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
'345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
// The second element of an original array is overwritten by the last element because of the same id
]
匿名関数は、グループ化配列でも使用できます。
$result = ArrayHelper::index($array, function ($element) {
return $element['id'];
});
3番目の引数としてid
を渡すと、$array
がid
でグループ化されます。
$result = ArrayHelper::index($array, null, 'id');
結果は、最初のレベルでid
でグループ化され、2番目のレベルでdevice
でグループ化され、3番目のレベルでdata
でインデックス付けされた多次元配列になります。
[
'123' => [
['id' => '123', 'data' => 'abc', 'device' => 'laptop']
],
'345' => [ // all elements with this index are present in the result array
['id' => '345', 'data' => 'def', 'device' => 'tablet'],
['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
]
]
匿名関数は、グループ化キーの配列でも使用できます。
$result = ArrayHelper::index($array, 'data', [function ($element) {
return $element['id'];
}, 'device']);
結果は、最初のレベルでid
でグループ化され、2番目のレベルでdevice
でグループ化され、3番目のレベルでdata
でインデックス付けされた多次元配列になります。
[
'123' => [
'laptop' => [
'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
]
],
'345' => [
'tablet' => [
'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
],
'smartphone' => [
'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
]
]
]
public static array index ( $array, $key, $groups = [] ) | ||
$array | array |
インデックス付けまたはグループ化する必要がある配列 |
$key | string|Closure|null |
配列のインデックスに使用される列名または匿名関数 |
$groups | string|string[]|Closure[]|null |
1つ以上のキーで入力配列をグループ化するために使用されるキーの配列。特定の要素に対する |
return | array |
インデックス付けおよび/またはグループ化された配列 |
---|
public static function index($array, $key, $groups = [])
{
$result = [];
$groups = (array) $groups;
foreach ($array as $element) {
$lastArray = &$result;
foreach ($groups as $group) {
$value = static::getValue($element, $group);
if (!array_key_exists($value, $lastArray)) {
$lastArray[$value] = [];
}
$lastArray = &$lastArray[$value];
}
if ($key === null) {
if (!empty($groups)) {
$lastArray[] = $element;
}
} else {
$value = static::getValue($element, $key);
if ($value !== null) {
if (is_float($value)) {
$value = StringHelper::floatToString($value);
}
$lastArray[$value] = $element;
}
}
unset($lastArray);
}
return $result;
}
定義元: yii\helpers\BaseArrayHelper::isAssociative()
指定された配列が連想配列かどうかを示す値を返します。
配列のすべてのキーが文字列の場合、その配列は連想配列です。$allStrings
がfalseの場合、少なくとも1つのキーが文字列であれば、配列は連想配列として扱われます。
空の配列は連想配列とは見なされないことに注意してください。
public static boolean isAssociative ( $array, $allStrings = true ) | ||
$array | array |
チェックされる配列 |
$allStrings | boolean |
配列を連想配列として扱うために、配列のキーがすべて文字列である必要があるかどうか。 |
return | boolean |
配列が連想配列かどうか |
---|
public static function isAssociative($array, $allStrings = true)
{
if (empty($array) || !is_array($array)) {
return false;
}
if ($allStrings) {
foreach ($array as $key => $value) {
if (!is_string($key)) {
return false;
}
}
return true;
}
foreach ($array as $key => $value) {
if (is_string($key)) {
return true;
}
}
return false;
}
定義元: yii\helpers\BaseArrayHelper::isIn()
配列または Traversable に要素が含まれているかどうかを確認します。
このメソッドはPHP関数in_array()と同じですが、さらにTraversableインターフェースを実装するオブジェクトでも機能します。
public static boolean isIn ( $needle, $haystack, $strict = false ) | ||
$needle | mixed |
検索する値。 |
$haystack | iterable |
検索する値のセット。 |
$strict | boolean |
厳密な( |
return | boolean |
|
---|---|---|
throws | yii\base\InvalidArgumentException |
|
public static function isIn($needle, $haystack, $strict = false)
{
if (!static::isTraversable($haystack)) {
throw new InvalidArgumentException('Argument $haystack must be an array or implement Traversable');
}
if (is_array($haystack)) {
return in_array($needle, $haystack, $strict);
}
foreach ($haystack as $value) {
if ($strict ? $needle === $value : $needle == $value) {
return true;
}
}
return false;
}
定義元: yii\helpers\BaseArrayHelper::isIndexed()
指定された配列がインデックス付き配列かどうかを示す値を返します。
配列のすべてのキーが整数の場合、その配列はインデックス付きです。$consecutive
がtrueの場合、配列キーは0から始まる連続したシーケンスである必要があります。
空の配列はインデックス付きと見なされることに注意してください。
public static boolean isIndexed ( $array, $consecutive = false ) | ||
$array | array |
チェックされる配列 |
$consecutive | boolean |
配列がインデックス付きとして扱われるために、配列のキーが連続したシーケンスである必要があるかどうか。 |
return | boolean |
配列がインデックス付きかどうか |
---|
public static function isIndexed($array, $consecutive = false)
{
if (!is_array($array)) {
return false;
}
if (empty($array)) {
return true;
}
$keys = array_keys($array);
if ($consecutive) {
return $keys === array_keys($keys);
}
foreach ($keys as $key) {
if (!is_int($key)) {
return false;
}
}
return true;
}
定義元: yii\helpers\BaseArrayHelper::isSubset()
配列または Traversable が別の配列または Traversable のサブセットであるかどうかを確認します。
このメソッドは、$needles
のすべての要素が $haystack
に含まれている場合に true
を返します。少なくとも1つの要素が見つからない場合は、false
が返されます。
public static boolean isSubset ( $needles, $haystack, $strict = false ) | ||
$needles | iterable |
|
$haystack | iterable |
検索する値のセット。 |
$strict | boolean |
厳密な( |
return | boolean |
|
---|---|---|
throws | yii\base\InvalidArgumentException |
|
public static function isSubset($needles, $haystack, $strict = false)
{
if (!static::isTraversable($needles)) {
throw new InvalidArgumentException('Argument $needles must be an array or implement Traversable');
}
foreach ($needles as $needle) {
if (!static::isIn($needle, $haystack, $strict)) {
return false;
}
}
return true;
}
定義元: yii\helpers\BaseArrayHelper::isTraversable()
変数が配列または Traversable であるかどうかを確認します。
このメソッドは PHP の関数 is_array() と同じですが、さらに Traversable インターフェースを実装するオブジェクトでも動作します。
public static boolean isTraversable ( $var ) | ||
$var | mixed |
評価される変数。 |
return | boolean |
$var が foreach でトラバース可能かどうか |
---|
public static function isTraversable($var)
{
return is_array($var) || $var instanceof Traversable;
}
定義元: yii\helpers\BaseArrayHelper::keyExists()
指定されたキーが配列に含まれているかどうかを確認します。
このメソッドは、大文字と小文字を区別しないキー比較をサポートすることで、array_key_exists()
関数を拡張します。
public static boolean keyExists ( $key, $array, $caseSensitive = true ) | ||
$key | string|integer |
チェックするキー |
$array | array|ArrayAccess |
チェックするキーを持つ配列 |
$caseSensitive | boolean |
キーの比較で大文字と小文字を区別するかどうか |
return | boolean |
配列に指定されたキーが含まれているかどうか |
---|
public static function keyExists($key, $array, $caseSensitive = true)
{
// ToDo: This check can be removed when the minimum PHP version is >= 8.1 (Yii2.2)
if (is_float($key)) {
$key = (int)$key;
}
if ($caseSensitive) {
if (is_array($array) && array_key_exists($key, $array)) {
return true;
}
// Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]]
return $array instanceof ArrayAccess && $array->offsetExists($key);
}
if ($array instanceof ArrayAccess) {
throw new InvalidArgumentException('Second parameter($array) cannot be ArrayAccess in case insensitive mode');
}
foreach (array_keys($array) as $k) {
if (strcasecmp($key, $k) === 0) {
return true;
}
}
return false;
}
定義元: yii\helpers\BaseArrayHelper::map()
多次元配列またはオブジェクトの配列からマップ (キーと値のペア) を作成します。
$from
パラメータと $to
パラメータは、マップを設定するためのキー名またはプロパティ名を指定します。必要に応じて、グルーピングフィールド $group
に従ってマップをさらにグループ化できます。
例:
$array = [
['id' => '123', 'name' => 'aaa', 'class' => 'x'],
['id' => '124', 'name' => 'bbb', 'class' => 'x'],
['id' => '345', 'name' => 'ccc', 'class' => 'y'],
];
$result = ArrayHelper::map($array, 'id', 'name');
// the result is:
// [
// '123' => 'aaa',
// '124' => 'bbb',
// '345' => 'ccc',
// ]
$result = ArrayHelper::map($array, 'id', 'name', 'class');
// the result is:
// [
// 'x' => [
// '123' => 'aaa',
// '124' => 'bbb',
// ],
// 'y' => [
// '345' => 'ccc',
// ],
// ]
public static array map ( $array, $from, $to, $group = null ) | ||
$array | array | |
$from | string|Closure | |
$to | string|Closure | |
$group | string|Closure|null |
public static function map($array, $from, $to, $group = null)
{
$result = [];
foreach ($array as $element) {
$key = static::getValue($element, $from);
$value = static::getValue($element, $to);
if ($group !== null) {
$result[static::getValue($element, $group)][$key] = $value;
} else {
$result[$key] = $value;
}
}
return $result;
}
定義元: yii\helpers\BaseArrayHelper::merge()
2つ以上の配列を再帰的に1つにマージします。
各配列に同じ文字列キー値を持つ要素がある場合、後者が前者を上書きします (array_merge_recursive とは異なります)。両方の配列が配列型の要素を持ち、同じキーを持っている場合は、再帰的なマージが実行されます。整数キー付き要素の場合、後者の配列の要素が前者の配列に追加されます。前の配列から値を設定解除するには、yii\helpers\UnsetArrayValue オブジェクトを使用するか、再帰的なマージの代わりに以前の値を強制的に置き換えるには、yii\helpers\ReplaceArrayValue を使用します。
public static array merge ( $a, $b ) | ||
$a | array |
マージされる配列 |
$b | array |
マージ元の配列。3番目の引数、4番目の引数などで追加の配列を指定できます。 |
return | array |
マージされた配列 (元の配列は変更されません)。 |
---|
public static function merge($a, $b)
{
$args = func_get_args();
$res = array_shift($args);
while (!empty($args)) {
foreach (array_shift($args) as $k => $v) {
if ($v instanceof UnsetArrayValue) {
unset($res[$k]);
} elseif ($v instanceof ReplaceArrayValue) {
$res[$k] = $v->value;
} elseif (is_int($k)) {
if (array_key_exists($k, $res)) {
$res[] = $v;
} else {
$res[$k] = $v;
}
} elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
$res[$k] = static::merge($res[$k], $v);
} else {
$res[$k] = $v;
}
}
}
return $res;
}
定義元: yii\helpers\BaseArrayHelper::multisort()
オブジェクトまたは配列 (同じ構造) の配列を、1つまたは複数のキーでソートします。
public static void multisort ( &$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR ) | ||
$array | array |
ソートされる配列。このメソッドを呼び出すと、配列が変更されます。 |
$key | string|Closure|array |
ソートするキー。これは、サブ配列要素のキー名、オブジェクトのプロパティ名、または比較のために値を返す匿名関数を指します。匿名関数のシグネチャは |
$direction | integer|array |
ソートの方向。 |
$sortFlag | integer|array |
PHPソートフラグ。有効な値には、 |
throws | yii\base\InvalidArgumentException |
$direction パラメータまたは $sortFlag パラメータに、$key の要素数と同じ数の要素がない場合。 |
---|
public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
{
$keys = is_array($key) ? $key : [$key];
if (empty($keys) || empty($array)) {
return;
}
$n = count($keys);
if (is_scalar($direction)) {
$direction = array_fill(0, $n, $direction);
} elseif (count($direction) !== $n) {
throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.');
}
if (is_scalar($sortFlag)) {
$sortFlag = array_fill(0, $n, $sortFlag);
} elseif (count($sortFlag) !== $n) {
throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.');
}
$args = [];
foreach ($keys as $i => $k) {
$flag = $sortFlag[$i];
$args[] = static::getColumn($array, $k);
$args[] = $direction[$i];
$args[] = $flag;
}
// This fix is used for cases when main sorting specified by columns has equal values
// Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
$args[] = range(1, count($array));
$args[] = SORT_ASC;
$args[] = SORT_NUMERIC;
$args[] = &$array;
call_user_func_array('array_multisort', $args);
}
定義元: yii\helpers\BaseArrayHelper::recursiveSort()
配列を再帰的にソートします。
public static array recursiveSort ( array &$array, $sorter = null ) | ||
$array | array |
参照渡しされる配列。 |
$sorter | callable|null |
配列ソーター。省略した場合、インデックス配列は値でソートし、連想配列はキーでソートします。 |
public static function recursiveSort(array &$array, $sorter = null)
{
foreach ($array as &$value) {
if (is_array($value)) {
static::recursiveSort($value, $sorter);
}
}
unset($value);
if ($sorter === null) {
$sorter = static::isIndexed($array) ? 'sort' : 'ksort';
}
call_user_func_array($sorter, [&$array]);
return $array;
}
定義元: yii\helpers\BaseArrayHelper::remove()
配列から項目を削除し、値を返します。キーが配列に存在しない場合は、代わりにデフォルト値が返されます。
使用例、
// $array = ['type' => 'A', 'options' => [1, 2]];
// working with array
$type = \yii\helpers\ArrayHelper::remove($array, 'type');
// $array content
// $array = ['options' => [1, 2]];
public static mixed|null remove ( &$array, $key, $default = null ) | ||
$array | array |
値を抽出する配列 |
$key | string |
配列要素のキー名 |
$default | mixed |
指定されたキーが存在しない場合に返されるデフォルト値 |
return | mixed|null |
要素が見つかった場合はその値、それ以外の場合はデフォルト値 |
---|
public static function remove(&$array, $key, $default = null)
{
// ToDo: This check can be removed when the minimum PHP version is >= 8.1 (Yii2.2)
if (is_float($key)) {
$key = (int)$key;
}
if (is_array($array) && array_key_exists($key, $array)) {
$value = $array[$key];
unset($array[$key]);
return $value;
}
return $default;
}
定義元: yii\helpers\BaseArrayHelper::removeValue()
一致する値を持つ項目を配列から削除し、削除された項目を返します。
例:
$array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
$removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
// result:
// $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
// $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
public static array removeValue ( &$array, $value ) | ||
$array | array |
値を検索する配列 |
$value | mixed |
配列から削除する値 |
return | array |
配列から削除された項目 |
---|
public static function removeValue(&$array, $value)
{
$result = [];
if (is_array($array)) {
foreach ($array as $key => $val) {
if ($val === $value) {
$result[$key] = $val;
unset($array[$key]);
}
}
}
return $result;
}
定義元: yii\helpers\BaseArrayHelper::setValue()
指定されたキーパスにある連想配列に値を書き込みます。
そのようなキーパスがまだ存在しない場合は、再帰的に作成されます。キーが存在する場合は、上書きされます。
$array = [
'key' => [
'in' => [
'val1',
'key' => 'val'
]
]
];
ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);
の結果は次のようになります。
[
'key' => [
'in' => [
['arr' => 'val'],
'key' => 'val'
]
]
]
ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);
または ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);
の結果は次のようになります。
[
'key' => [
'in' => [
'arr' => 'val'
]
]
]
public static void setValue ( &$array, $path, $value ) | ||
$array | array |
値を書き込む配列 |
$path | string|array|null |
|
$value | mixed |
書き込む値 |
public static function setValue(&$array, $path, $value)
{
if ($path === null) {
$array = $value;
return;
}
$keys = is_array($path) ? $path : explode('.', $path);
while (count($keys) > 1) {
$key = array_shift($keys);
if (!isset($array[$key])) {
$array[$key] = [];
}
if (!is_array($array[$key])) {
$array[$key] = [$array[$key]];
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
}
定義元: yii\helpers\BaseArrayHelper::toArray()
オブジェクトまたはオブジェクトの配列を配列に変換します。
public static array toArray ( $object, $properties = [], $recursive = true ) | ||
$object | object|array|string |
配列に変換するオブジェクト |
$properties | array |
オブジェクトのクラス名から、結果の配列に入れる必要のあるプロパティへのマッピング。各クラスに指定されたプロパティは、次の形式の配列です。
|
$recursive | boolean |
オブジェクトであるプロパティを再帰的に配列に変換するかどうか。 |
return | array |
オブジェクトの配列表現 |
---|
public static function toArray($object, $properties = [], $recursive = true)
{
if (is_array($object)) {
if ($recursive) {
foreach ($object as $key => $value) {
if (is_array($value) || is_object($value)) {
$object[$key] = static::toArray($value, $properties, true);
}
}
}
return $object;
} elseif ($object instanceof \DateTimeInterface) {
return (array)$object;
} elseif (is_object($object)) {
if (!empty($properties)) {
$className = get_class($object);
if (!empty($properties[$className])) {
$result = [];
foreach ($properties[$className] as $key => $name) {
if (is_int($key)) {
$result[$name] = $object->$name;
} else {
$result[$key] = static::getValue($object, $name);
}
}
return $recursive ? static::toArray($result, $properties) : $result;
}
}
if ($object instanceof Arrayable) {
$result = $object->toArray([], [], $recursive);
} else {
$result = [];
foreach ($object as $key => $value) {
$result[$key] = $value;
}
}
return $recursive ? static::toArray($result, $properties) : $result;
}
return [$object];
}
サインアップ または ログイン してコメントしてください。