【问题标题】:Insert array at desired index into an associate array of arrays将所需索引处的数组插入到关联的数组数组中
【发布时间】:2017-09-20 06:05:13
【问题描述】:

我有一个像下面这样的数组

$arr=array(

    array(

        'id'=> 342,
        'name' =>'srikanth',
        'age' => 32
    ),
    array(

        'id'=> 409,
        'name' =>'Ashok',
        'age' => 24
    ),
    array(

        'id'=> 314,
        'name' =>'Chakri',
        'age' => 25
    ),
    array(

        'id'=> 208,
        'name' =>'saikiran',
        'age' => 27
    )

);

我必须从数组中寻找一个特定的 id,例如 id=409,我在下面这样做

$key=array_search("409",array_column($arr,"id"));

并将数组复制到下面的临时变量并取消设置:

$tmp=$arr[$key];


unset($arr[$key]);

现在我想要的是在 $arr 中我想要的索引处插入临时数组。

我使用下面的函数插入到我想要的索引中,但没有得到想要的结果。

function insertAt($array = [], $item = [], $position = 0) {
    $previous_items = array_slice($array, 0, $position, true);
    $next_items     = array_slice($array, $position, NULL, true);
    return $previous_items + $item + $next_items;
}


$arr=insertAt($arr,$tmp,0);

我希望临时数组位于 0 索引处(并不总是位于 0 索引处,我知道 array_unshift :))并且我的结果数组应该如下所示。

$arr=array(

    array(

        'id'=> 409,
        'name' =>'Ashok',
        'age' => 24
    ),
    array(

        'id'=> 342,
        'name' =>'srikanth',
        'age' => 32
    ),
    array(

        'id'=> 314,
        'name' =>'Chakri',
        'age' => 25
    ),
    array(

        'id'=> 208,
        'name' =>'saikiran',
        'age' => 27
    )

);

【问题讨论】:

  • 使用array_splice()。它删除零个或多个元素并插入零个或多个元素而不是删除的元素。

标签: php arrays associative-array array-push


【解决方案1】:

array_splice() 为您完成这项工作:

// Find current position
$key = array_search(409, array_column($arr, 'id'));

// Get the element
$tmp = $arr[$key];

// Remove it from array
unset($arr[$key]);

// Insert it at a new position
$position = 0;
$arr = array_splice($arr, $position, 0, array($tmp));

【讨论】:

  • 完美解决方案.. +1
猜你喜欢
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
相关资源
最近更新 更多