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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀