Take values from an Array and implement within Json using php

Asked

Viewed 119 times

1

How do I get the values of this array

 array(2) {["Premium"]=>array(3) {["valor"]=> string(3) "100" ["quantidade"]=> string(3) "200" ["status"]=> string(1) "1" } ["Arena"]=> array(3) { ["valor"]=> string(2) "50" ["quantidade"]=> string(3) "200" ["status"]=> string(1) "1" } }

and change the values of the following json

{"3":{"tipo":"Premium","valor":"100","quantidade":"200","vendas":"0","status":"1"},"1":{"tipo":"Arena","valor":"50","quantidade":"200","vendas":"0","status":"1"}}

According to its types, for example the [Premium] Array changes the json values that contain the "type":"Premium".

1 answer

1


From what I understand you want to change all the values ofjsonusing the values of the array. So I created a solution that goes through all the elements of json and checks whether the 'type' attribute is contained in the index of array. If it is, change the values of json using the values and indices of array:

Commented code

    $array = [
        'Premium' => ['valor' => '350', 'quantidade' => '50', 'status' => '1'],
        'Arena' => ['valor' => '250', 'quantidade' => '10', 'status' => '1']
    ];
    $json = '{"3":{"tipo":"Premium","valor":"100","quantidade":"200","vendas":"0","status":"1"},"1":{"tipo":"Arena","valor":"50","quantidade":"200","vendas":"0","status":"1"}}';

    $json = json_decode($json, true); // tranforma o json em array para a comparação

    $keys = array_keys($array); // pega as chaves do array

    // loop em cada elemento
    foreach($json as $key => $val){
        // se houver o indice no array que for igual ao tipo, iguala os valore do array
        if(in_array($val['tipo'], $keys)){
            $json[$key]['valor'] = $array[$val['tipo']]['valor']; // altera o valor
            $json[$key]['quantidade'] = $array[$val['tipo']]['quantidade']; // altera a quantidade
            $json[$key]['status'] = $array[$val['tipo']]['status']; // altera o status
        }
    }
    print_r(json_encode($json));
  • When I change the value in the array it is not modified in json!

  • @Joãopedro sorry, it’s sleep! = ) It’s there!

  • 1

    Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.