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 被蓝屏搞吐了,有偿求帮解答,Ai回复直接拉黑
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角