PHP Searching multidimensional associative array

我怕爱的太早我们不能终老 提交于 2019-12-11 17:55:05

问题


I am trying to search a multi-dimensional associative array and change a value after searching. Here is what my array looks like

 $arr=Array ( [0] => Array ( [1] => 
    Array ( [keyword] => 2014 
            [count] => 97 
            [percent] => 4.91 )))

So what I am trying to do is to search for keyword and if found then increase the count on that particular index where keyword was found.

So I am trying to do something like:

if(in_array("2014", $arr))
{
//then add 100 to count that is 100+97

}

So what will be the best way to go about this.

Note: I am trying to search a value in the array and if found then update the value of count key on that particular index. The last part is as important as first.

Ahmar


回答1:


you can use that code:

$arr = Array(
    0 => Array(
        1 => Array(
            'keyword' => 2014,
            'count' => 97,
            'percent' => 4.91
        )
    )
);

foreach ($arr as &$arr1) {

    foreach ($arr1 as &$arr2) {

        if (2014 == $arr2['keyword']) {
            $arr2['count'] += 100;
        }

    }
}

unset($arr2, $arr1);

Result:

array(1) {
  [0]=>
  array(1) {
    [1]=>
    array(3) {
      ["keyword"]=>
      int(2014)
      ["count"]=>
      int(197)
      ["percent"]=>
      float(4.91)
    }
  }
}



回答2:


iterate through the dimensions of the array and change value if you found the key

foreach ($arr as $key => $val) {
    foreach ($arr[$key] as $keyy => $val) {
        foreach ($arr[$key][$keyy] as $keyyy => $val) {
            if($arr[$key][$keyy]['keyword'] == 2014){
                $arr[$key][$keyy]['count'] = $arr[$key][$keyy]['count']+100;
                break;
            }
        }          
    }       
}

hope it helps ;D




回答3:


Your array

$arr=array( "0" => array( "1" => 
    array( "keyword" => 2014 ,
            "count" => 97, 
            "percent" => 4.91 ),
  "2"=> array( "keyword" => 2015,
            "count" => 5, 
            "percent" => 4.91 )));

Code

foreach($arr as $key => &$val) {

    foreach($val as $mm => &$aa) {

        if("2014" == $aa['keyword']) {

            $aa["count"] =  $aa["count"]+ 100;
        }
    }
}

print_r($arr);

Sandbox url: http://sandbox.onlinephpfunctions.com/code/fc2fd3a5bd3593c88efdb50c4a57b0812a7512c9



来源:https://stackoverflow.com/questions/24340649/php-searching-multidimensional-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!