How to enter values to an array with the key in php?

3

I have the following array

For example the array (0) in data tiene {3:1.30} what I want to do is fill in the positions (0,1,2) with the value of 0. It is say that it is in%% data_of%.
For example the array (1) in {0:0,1:0,2:0,3:1.30} what I want to do is fill the positions (1) with the value of 0. That is to say that it is in data data tiene {0:0.31,2:0.74,3:0.69} .

What I did was this but nothing comes out, it does not add the values it stays the same

foreach ($causales as $row_causales){
    foreach ($row_causales['data'] as $key => $row_data ){
        for ($j=0;$j<=3;$j++){
            if($i!==$key){
                $causales[$i]['data'][$j] = 0;
            }
        }
    }
    $i++;
}
    
asked by ingswsm 24.08.2018 в 20:29
source

1 answer

0

You do not need to go through the array data . You can do it with the internal for from 0 to 3 and check if the values exist in the keys of data using array_keys and in_array . You also need to add & to the variable $row_causales to be able to edit the values. It would be something like this:

foreach ($causales as &$row_causales){
    $keys = array_keys($row_causales['data']);
    for ($j=0;$j<=3;$j++){
        if(!in_array($j,$keys)){
             $row_causales['data'][$j] = 0;
        }         
    }
    ksort($row_causales['data']);
}
    
answered by 24.08.2018 / 20:43
source