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

How to replace array elements in php?

coldplay.xixi
coldplay.xixiOriginal
2020-07-17 14:39:223060browse

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 [6d267e5fab17ea8bc578f9e7e5e1570b] 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;
'; ?>

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 6d267e5fab17ea8bc578f9e7e5e1570b 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 "
"; ?>

The output result of the above example is:

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

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!

Statement:
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