如何复制数组中的一个特殊元素

时间:2016-10-12 13:20:17

标签: php arrays

我有这个数组

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
  ]
]

我希望find元素有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 个答案:

答案 0 :(得分:2)

一个简单的解决方案:

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

Voila,您的$new_arrs将获得所需的结果。

答案 1 :(得分:0)

考虑,数组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++;
  }
}

希望这就是你想要的。