[英]How to set php array index as array value…?
我有一個查詢數組。
Array
(
[0] => Array
(
[user_id] => 5
[first_name] => Diyaa
[profile_pic] => profile/user5.png
)
[1] => Array
(
[user_id] => 8
[first_name] => Raj
[profile_pic] => profile/user8.jpg
)
[2] => Array
(
[user_id] => 10
[first_name] => Vanathi
[profile_pic] => profile/user10.jpg
)
)
我需要將數組索引設置為類似於數組值 ( user_id
),如下所示:
Array
(
[5] => Array
(
[user_id] => 5
[first_name] => Diyaa
[profile_pic] => profile/user5.png
)
[8] => Array
(
[user_id] => 8
[first_name] => Raj
[profile_pic] => profile/user8.jpg
)
[10] => Array
(
[user_id] => 10
[first_name] => Vanathi
[profile_pic] => profile/user10.jpg
)
)
注意: user_id
是一個唯一值,將不再重復。 無需擔心索引值。
如何轉換並獲取該數組作為指定的索引值。
您可以嘗試這段代碼,在這里我做了一些額外的工作。 請參閱AbraCadaver的聰明答案$result = array_column($array, null, 'user_id');
。
array_combine(array_column($array, 'user_id'), $array);
這正是array_column()
的用途:
$result = array_column($array, null, 'user_id');
array_column()從輸入的單個列中返回由column_key標識的值。 可選地,可以提供index_key以通過輸入數組的index_key列中的值索引返回的數組中的值。
column_key
要返回的值列。 此值可以是您要檢索的列的整數鍵,也可以是關聯數組或屬性名稱的字符串鍵名。 返回完整的數組或對象也可能為NULL(這與index_key一起用於重新索引數組很有用)。
兩種結構都不必要地復雜和多余。 為什么不
$foo = array(5 =>
array('first_name' => 'Diyaa',
'profile_pic' => 'profile/user5.png'),
8 =>
array('first_name' => 'Raj',
'profile_pic' => 'profile/user8.png'),
...
);
然后通過$foo[$user_id]
訪問它,這將為您提供2元素關聯數組,例如
array('first_name' => 'Raj',
'profile_pic' => 'profile/user8.png'),
要更改profile_pic:
$foo[$user_id]['profile_pic'] = $new_pic;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.