2015-04-17 78 views
1

我有以下的數組:轉換索引陣列,用於循環

$all_items = Array 
(
    [0] => abc 
    [1] => bcd 
    [2] => cde 
    [3] => def 
    [4] => efg 
) 

我想轉此數組關聯數組像的下方。

array(
     array('A'=>abc, 'position'=>0), 
     array('A'=>bcd, 'position'=>1), 
     array('A'=>cde, 'position'=>2), 
     array('A'=>abc, 'position'=>3), 
     array('A'=>bcd, 'position'=>4) 
), 

到目前爲止,我已經嘗試了許多不同的方法,沒有運氣。這是我的代碼。

$k = 0; 
    foreach($all_items as $item) { 
    $all_items[$key]['src'] =$item; 
    $all_items[$key]['position']=i; 
    $k++; 
    }; 

我錯過了什麼?

+0

FYI:您可以接受的答案如何幫助您最和解決您的問題(http://meta.stackexchange.com/q/5234)! – Rizier123

回答

4

這應該是相當簡單的,試試這個方法:通過與陣列

(在這裏,我只是循環:

<?php 
$items = array(); 
foreach($all_items as $k=>$v) { 
    $items[] = array(
    'A' => $v, 
    'position' => $k 
); 
} 
1

嘗試 -

$newArr = array_map('buildArr', $all_items, array_keys($all_items)); 

function buildArr($data, $key) { 
    $result = array('A' => $data, 'position' => $key); 
    return $result; 
} 
var_dump($newArr); 
3

這應該爲你工作array_map()併爲每個值返回一個新數組)

<?php 

    $all_items = ["abc", "bcd", "cde", "def", "efg"]; 

    $result = array_map(function($v, $k){ 
     return ["A" => $v, "position" => $k]; 
    }, $all_items, array_keys($all_items)); 

    print_r($result); 

?> 

輸出:

Array 
(
    [0] => Array 
     (
      [A] => abc 
      [position] => 0 
     ) 
    //... 

    [4] => Array 
     (
      [A] => efg 
      [position] => 4 
     ) 

)