![](/img/trans.png)
[英]How can i change the key of the array with the value of the same array in PHP?
[英]How can I change key in the array on the php?
我的數組是這樣的:
$arr = array('chelsea.jpg', 'arsenal.jpg');
如果我運行: echo '<pre>';print_r($arr);echo '</pre>';
結果 :
Array
(
[0] => chelsea.jpg
[1] => arsenal.jpg
)
我想換鑰匙。 所以結果是這樣的:
Array
(
[cover1] => chelsea.jpg
[cover2] => arsenal.jpg
)
我該怎么做?
您可以使用經典的foreach
$arr = array('chelsea.jpg', 'arsenal.jpg');
$final = array();
foreach( $arr as $key => $val ) {
//Notice that $key + 1 -> because the first key of a simple array is 0
//You are assigning here the NEW key inside []
$final[ "cover" . ( $key + 1 ) ] = $val;
}
echo "<pre>";
print_r( $final );
echo "</pre>";
這將導致
Array
(
[cover1] => chelsea.jpg
[cover2] => arsenal.jpg
)
$arr = array( 'cover1' => 'chelsea.jpg', 'cover2' => 'arsenal.jpg' );
您可以使用array_combine()。
print_r(array_combine(array('cover1', 'cover2'), array('chelsea.jpg', 'arsenal.jpg')));
動態生成密鑰-
$values = array('chelsea.jpg', 'arsenal.jpg');
// Generate keys depending on the count of values
$keys = array_map(function($k) {
return 'cover' . $k;
}, range(1, count($values)));
print_r(array_combine($keys, $values));
輸出量
Array
(
[cover1] => chelsea.jpg
[cover2] => arsenal.jpg
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.