donglipi4495 2017-09-20 06:05
浏览 46
已采纳

将所需索引处的数组插入到数组的关联数组中

I have a array like below

$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
    )

);

I have to look for a specific id from the array for example id=409 which i am doing like below

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

and copying the array to a temp variable like below and unsetting it:

$tmp=$arr[$key];


unset($arr[$key]);

Now what i want is to insert the temp array at my desired index in $arr.

I used below function to insert into my desired index but failed to get desired result.

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);

I want the temp array at 0 index (Not always at 0 index i know about array_unshift :) ) and my result array should look like this.

$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
    )

);
  • 写回答

1条回答 默认 最新

  • dougan6402 2017-09-20 06:22
    关注

    array_splice() does the job for you:

    // 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));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大