Search code examples
phpjsonlaravelnaivebayesjsondecoder

How can I multiply all item in an array with laravel?


i have array in controller with output like this

{
  "usia": 0.01761252446184,
  "wife_education": 0.078277886497065,
  "husband_education": 0.0058708414872798,
  "number_of_children": 0.17025440313112,
  "wife_religion": 0.86497064579256,
  "wife_now_working": 0.078277886497065,
  "husband_occupation": 0.23874755381605,
  "living_index": 0.078277886497065,
  "media_exposure": 0.048923679060665
 }

I would like to multiply each element of my array, example like this

(usia * wife_education * husband_education * number_of_children * wife_religion * wife_now_working * husband_occupation * living_index * media_exposure)


Solution

  • Put your data in string and decode in JSON:

    $data = '{  
        "usia": 0.01761252446184,  
        "wife_education": 0.078277886497065,  
        "husband_education": 0.0058708414872798,  
        "number_of_children": 0.17025440313112,  
        "wife_religion": 0.86497064579256,  
        "wife_now_working": 0.078277886497065,  
        "husband_occupation": 0.23874755381605,  
        "living_index": 0.078277886497065,  
        "media_exposure": 0.048923679060665  
    }';
    
    
    $data = json_decode($data, true);
    

    Then loop through the $data for multiplication as:

    $product = 1;
    foreach ($data as $key => $value) {
        $product *= $value;
    }