2016-10-12 64 views
0

複製一個特殊的元素我有這樣的陣列如何在陣列

array:4 [ 
    0 => array:4 [ 
    "id" => 829 
    "lat" => "26.5200389" 
    "lng" => "128.0209283" 
    "right_angle" => 1 
    ] 
    1 => array:4 [ 
    "id" => 830 
    "lat" => "26.5197977" 
    "lng" => "128.0213830" 
    "right_angle" => 0 
    ] 
    2 => array:4 [ 
    "id" => 831 
    "lat" => "26.5200101" 
    "lng" => "128.0213830" 
    "right_angle" => 1 
    ] 
    3 => array:4 [ 
    "id" => 832 
    "lat" => "26.5199837" 
    "lng" => "128.0217600" 
    "right_angle" => 0 
    ] 
] 

而且我想找到元素有right_angle = 1和此數組中複製它。

這個結果將是

array:6 [ 
    0 => array:4 [ 
    "id" => 829 
    "lat" => "26.5200389" 
    "lng" => "128.0209283" 
    "right_angle" => 1 
    ] 
    1 => array:4 [ 
    "id" => 829 
    "lat" => "26.5200389" 
    "lng" => "128.0209283" 
    "right_angle" => 1 
    ] 
    2 => array:4 [ 
    "id" => 830 
    "lat" => "26.5197977" 
    "lng" => "128.0213830" 
    "right_angle" => 0 
    ] 
    3 => array:4 [ 
    "id" => 831 
    "lat" => "26.5200101" 
    "lng" => "128.0213830" 
    "right_angle" => 1 
    ] 
    4 => array:4 [ 
    "id" => 831 
    "lat" => "26.5200101" 
    "lng" => "128.0213830" 
    "right_angle" => 1 
    ] 
    5 => array:4 [ 
    "id" => 832 
    "lat" => "26.5199837" 
    "lng" => "128.0217600" 
    "right_angle" => 0 
    ] 
] 

我發現這個

function array_insert_after(array $array, $key, array $new) { 
    $keys = array_keys($array); 
    $index = array_search($key, $keys); 
    $pos = false === $index ? count($array) : $index + 1; 
    return array_merge(array_slice($array, 0, $pos), $new, array_slice($array, $pos)); 
} 

但這函數只是一個特殊的項目工作。如果我的數組有2個特殊項目。 key將是錯誤的位置。

回答

2

一個簡單的辦法:

foreach ($arrs as $arr) { 
    if ($arr["right_angle"] === 1) { 
     $new_arrs[] = $arr; 
     $new_arrs[] = $arr; 
    } 
    else $new_arrs[] = $arr; 
} 

瞧,你$new_arrs將有希望的結果。

+1

真的非常感謝你!那就對了! –

0

考慮,Array arr; let int specialKeysCount = 0;

for (int i=0; i < (arr.size() + specialKeysCount); i++){ 
    if(arr.get(i).right_angle == 1){ 
    arr.add(arr.get(i),++i); //where ++i will be new position were    
           object will be repeated 
    specialKeysCount++; 
    } 
} 

希望這是你想要的。