Home > Backend Development > PHP Problem > How to replace array elements in php?

How to replace array elements in php?

coldplay.xixi
Release: 2023-03-02 16:36:01
Original
3169 people have browsed it

php method to replace array elements: 1. Replace the key of the array with the KEY value, the code is [$arr[$i][name] = $array[$i][shop_name]]; 2. Use To recursively replace the contents of the array, replace [< >] in the array with [{ }].

How to replace array elements in php?

php method to replace array elements:

Although there are many functions for processing arrays in php, some The function also needs to be encapsulated by ourselves, for example, replacing the elements in the array:

The following is to replace the key of the array with the KEY value:

<?php
 
$arr = array();
$array = array(
    0 => array(shop_name=>1,shop_id=>2),
    1 => array(shop_name => 2, shop_id=>3)
);
 
for($i=0; $i<count($array); $i++) {
    $arr[$i][name] = $array[$i][shop_name];
$arr[$i][id]=$array[$i][shop_id];
}
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r ($arr);
echo &#39;
'; ?>
Copy after login

The following example is a method of encapsulation:

Develop a small trick example program and use recursion to replace the contents of the array.

Replace < > in the array with { }.

You can use this function according to the actual situation. It is very convenient to replace elements in the array;

<?php
    $arr = array("<小刚>","<小晓>","<小飞>","<小李>","<小红>");
    function arrContentReplact($array)
    {
        if(is_array($array))
        {
            foreach($array as $k => $v)
            {
                $array[$k] = arrContentReplact($array[$k]);
            }
        }else
        {
            $array = str_replace(array(&#39;<&#39;, &#39;>&#39;), array(&#39;{&#39;, &#39;}&#39;), $array);
        }
        return $array;
    }
   
    $arr3 = arrContentReplact($arr);
   
    echo "<pre class="brush:php;toolbar:false">";
    print_r($arr3);
    echo "
"; ?>
Copy after login

The output result of the above example is:

Array
(
    [0] => {小刚}
    [1] => {小晓}
    [2] => {小飞}
    [3] => {小李}
    [4] => {小红}
)
Copy after login

Related learning recommendations: PHP programming from entry to proficiency

The above is the detailed content of How to replace array elements in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template