学习使用php实现在数组指定位置、键插入元素

该博客介绍了如何使用PHP的array_splice_assoc函数在数组的指定位置或键插入元素。示例代码展示了如何在关联数组中插入新元素,并保持数组的结构完整。通过json_decode将JSON字符串转换为PHP数组,然后在键'284_answer_text'之前插入新元素'283_answer_text'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习使用php实现在数组指定位置、键插入元素

函数解析

array_flip — 交换数组中的键和值
array_slice — 从数组中取出一段

示例代码


/**
 * @param $input [需要修改的数组]
 * @param $offset [插入的起始位置或键名后]
 * @param $length [插入的长度或键名前]
 * @param $replacement [需要插入的元素(array、string....)]
 * @return array
 */
function array_splice_assoc(&$input, $offset, $length = 0, $replacement = array())
{
    $replacement = (array)$replacement;
    $key_indices = array_flip(array_keys($input));

    if (isset($input [$offset]) & is_string($offset)) {
        $offset = $key_indices [$offset];
    }
    if (isset($input[$length]) && is_string($length)) {
        $length = $key_indices [$length] - $offset;
    }

    // 先取出添加位置之前的元素与要添加的元素合并,再取添加位置之后的元素再合并
    $result = array_slice($input, 0, $offset, TRUE)
        + $replacement
        + array_slice($input, $offset + $length, NULL, TRUE);

    return $result;
}


$input_str = '{"member_name":"徊忆","address":"北京市市辖区朝阳区","create_time":"2022年03月03日 13时12分56秒","sum_score":10,"284_answer_text":"A、正确(回答:√得5分)","285_answer_text":"司马迁(回答:√得5分)","287_answer_text":"119(回答:×得0分)"}';
$input = json_decode($input_str, true);

echo "原数组<pre>";
print_r($input );

$replacement = ['283_answer_text' => '李白'];
$offset = '284_answer_text';

//截取长度
$length = 0;


$result = array_splice_assoc($input, $offset, $length, $replacement);

echo "新数组<pre>";
print_r($result);

打印结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值