PHP-替换多维数组中的数据,特定键 [英] PHP - Replace data within multidimensional array, specific key

查看:481
本文介绍了PHP-替换多维数组中的数据,特定键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习PHP,因此抱歉可能是一个基本问题.我找不到答案.

I'm relearning PHP, so sorry for might be a basic question. I can't find an answer.

我有一个多维数组,我需要用另一个值替换特定键(所有实例)的值.

I have a multidimensional array, I need to replace the value for a specific key (all instances of) with another value.

Array ( 
    [13] => Array ( 
                [ad_id] => 13 
                [ad_name] => Qhxxst 
                [ad_link] => www.qxxst.co.uk 
                [ad_type] => 1 
            ) 
    [15] => Array ( 
                [ad_id] => 15 
                [ad_name] => Pxxly 
                [ad_link] => http://pixxly.net 
                [ad_type] => 1 
            ) 
    [16] => Array ( 
                [ad_id] => 16 
                [ad_name] => cxxm 
                [ad_link] => http://www.cxxm.co.uk 
                [ad_type] => 1 
            ) 
)

我希望将ad_type的所有实例替换为另一个值. IE. 如果ad_type = 1,则替换为x 如果ad_type = 2,则替换为y

I wish to replace all instances of ad_type with another value. i.e. Where ad_type = 1, replace with x Where ad_type = 2, replace with y

我一直在使用str_replacejson_decode,但没有成功.它们要么替换所有"1"的实例,要么根本不替换任何实例.我只需要定位ad_type键.

I've been using str_replace and json_decode without success. They either replace all instances of '1' or nothing at all. I need to target ad_type keys only.

推荐答案

访问数组键和值的最佳方法是使用foreach循环.

Best way to access the keys and values of an array is with foreach loop.

类似的东西:

$array= Array ( [13] => Array ( [ad_id] => 13 [ad_name] => Qhxxst [ad_link] => www.qxxst.co.uk [ad_type] => 1 ) [15] => Array ( [ad_id] => 15 [ad_name] => Pxxly [ad_link] => http://pixxly.net [ad_type] => 1 ) [16] => Array ( [ad_id] => 16 [ad_name] => cxxm [ad_link] => http://www.cxxm.co.uk [ad_type] => 1 ) );

foreach ($array as $key=>$val) 
{
    if ($key=="ad_type" && $val==1) 
    {
        $val="x";
    }
    elseif ($key=="ad_type" && $val==2) 
    {
        $val="y";
    }
}

进一步参考 http://php.net/manual/zh/control-structures.foreach.php

这篇关于PHP-替换多维数组中的数据,特定键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆