current position:Home>Learn to use PHP to insert elements at the specified position and key of the array

Learn to use PHP to insert elements at the specified position and key of the array

2022-04-29 16:05:13Lingering memory of Yufei

Learn to use php Implement at the specified position in the array 、 Key insert element

Function analysis

array_flip —  Swap keys and values in an array 
array_slice —  Take a segment from the array 

Sample code


/** * @param $input [ The array that needs to be modified ] * @param $offset [ After the starting position or key name of the insert ] * @param $length [ Inserted length or before key name ] * @param $replacement [ Elements to insert (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;
    }

    //  First take out the element before the adding position and merge it with the element to be added , Then take the elements after the addition position and merge them 
    $result = array_slice($input, 0, $offset, TRUE)
        + $replacement
        + array_slice($input, $offset + $length, NULL, TRUE);

    return $result;
}


$input_str = '{"member_name":" Wandering memory ","address":" Chaoyang District, Beijing Municipality ","create_time":"2022 year 03 month 03 Japan  13 when 12 branch 56 second ","sum_score":10,"284_answer_text":"A、 correct ( answer :√ have to 5 branch )","285_answer_text":" Sima Qian ( answer :√ have to 5 branch )","287_answer_text":"119( answer :× have to 0 branch )"}';
$input = json_decode($input_str, true);

echo " Original array <pre>";
print_r($input );

$replacement = ['283_answer_text' => ' Li Bai '];
$offset = '284_answer_text';

// Interception length 
$length = 0;


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

echo " New array <pre>";
print_r($result);

Print the results
 Insert picture description here

copyright notice
author[Lingering memory of Yufei],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291425562098.html

Random recommended