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

学习使用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);

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

猜你喜欢

转载自blog.csdn.net/guo_qiangqiang/article/details/123274850