如果第0个位置匹配,Php添加第1个位置的数组值

时间:2016-12-24 04:35:20

标签: php arrays codeigniter

Array ( [Hydraulics] => Array ( [0] => Array ( [0] => Lesson1 [1] => 1 ) [1] => Array ( [0] => Lesson3 [1] => 1 ) [3] => Array ( [0] => Lesson1 [1] => 1 ) [4] => Array ( [0] => Lesson2 [1] => 1 ) [5] => Array ( [0] => Lesson3 [1] => 1 ) ) [Waste Water Engineering] => Array ( [0] => Array ( [0] => Lesson1 [1] => 1 ) [1] => Array ( [0] => Lesson2 [1] => 1 ) [2] => Array ( [0] => Lesson3 [1] => 0 ) ) [RCC Structure Design] => Array ( [0] => Array ( [0] => Lesson1 [1] => 1 ) [1] => Array ( [0] => Lesson2 [1] => 1 ) [2] => Array ( [0] => Lesson3 [1] => 1 ) ) [Irrigation] => Array ( [0] => Array ( [0] => Lesson1 [1] => 0 ) [1] => Array ( [0] => Lesson2 [1] => 1 ) [2] => Array ( [0] => Lesson3 [1] => 1 ) ) [Plastic Blocks] => Array ( [0] => Array ( [0] => Lesson1 [1] => 1 ) [1] => Array ( [0] => Lesson2 [1] => 1 ) [2] => Array ( [0] => Lesson3 [1] => 1 ) ) )

如果您看到Hydraulics array lesson1出现2次。我想添加要添加的Lesson1第一个位置值并删除其他重复条目。我想将数据提供给谷歌图表。我删除了一些数组部分,因为它太长了。

1 个答案:

答案 0 :(得分:0)

你可以简单地遍历数组来找到相同的值,你也可以添加和删除它们,检查下面的代码来理解,我希望这对你有用。

<?php 
$array['Hydraulics'] = array ( 
                            0 => array ( 0 => 'Lesson1', 1 => 1 ),
                            1 => array ( 0 => 'Lesson3', 1 => 1 ),
                            3 => array ( 0 => 'Lesson1', 1 => 1 ), 
                            4 => array ( 0 => 'Lesson2', 1 => 1 ),
                            5 => array ( 0 => 'Lesson3', 1 => 1 ) 
                        );

$checked_keys=array(); //array to store checked keys.
foreach($array['Hydraulics'] as $key1 =>$val1){  ///first loop
    $string1 = $val1[0];  //value at key 0 for each node eg. Lesson1,Lesson3 etc
    foreach($array['Hydraulics'] as $key2 => $val2){ ///again loop the same array for finding same values
        $string2 = $val2[0]; //value at key 0 for each node eg. Lesson1,Lesson3 etc
        if($string1==$string2 && $key2 != $key1 && !in_array($key2,$checked_keys)){ //will go further only value matches and key of first loop != second loop
            $array['Hydraulics'][$key1][1] =  $val1[1]+$val2[1]; //add the values and index 1.
            $checked_keys[]= $key1; ///push chekced keys in array for skipping next time.
            unset($array['Hydraulics'][$key2]); //unset the duplicate values.
        }   
    }
}       
echo "<pre>";print_r($array);//output                        
?>

这会给你:

Array
(
    [Hydraulics] => Array
        (
            [0] => Array
                (
                    [0] => Lesson1
                    [1] => 2
                )

            [1] => Array
                (
                    [0] => Lesson3
                    [1] => 2
                )

            [4] => Array
                (
                    [0] => Lesson2
                    [1] => 1
                )

        )

)

CLICK HERE FOR LIVE DEMO