Home > Software design >  PHP - Change only value with '0' to string 'Free'
PHP - Change only value with '0' to string 'Free'

Time:12-15

I just simplified JSON data i have cause i need only two values from it. I filtered what I need as you can see in code below but in some values are 0 and on output only that zero need to be as new value 'Free'.

Here is the code what i get for now:

    $json = '[{"Number":"333567","Cost":0},{"Number":"333568","Cost":7500},{"Number":"333569","Cost":7500}]';
    $options = json_decode($json, true);

        $newArray = [];
        foreach ($options as $key => $value) {
            $newArray[$value['Number']]= $value['Number']." "."£".$value['Cost'] / 100;
        }
    echo '<br>';
    echo '<br>';

    print_r($newArray);

The results what i got is:

Array ( [333567] => 333567 £0 [333568] => 333568 £75 [333569] => 333569 £75 )

But i need on output only £0 be Free like this:

Array ( [333567] => 333567 Free [333568] => 333568 £75 [333569] => 333569 £75 )

CodePudding user response:

$newArray[$value['Number']]= $value['Number']." ".($value['Cost'] / 100 == 0 ? 'Free': "&pound;".$value['Cost'] / 100);

I hope It will solve your problem

CodePudding user response:

you can try $value['Cost'] / 100 > 0 ? $value['Cost'] : 'free' with your code is below

    $json = '[{"Number":"333567","Cost":0},{"Number":"333568","Cost":7500},{"Number":"333569","Cost":7500}]';
    $options = json_decode($json, true);

        $newArray = [];
        foreach ($options as $key => $value) {
            $newArray[$value['Number']]= $value['Number']." "."&pound;".($value['Cost'] / 100 > 0 ? $value['Cost'] : 'free');
        }
    echo '<br>';
    echo '<br>';

    print_r($newArray);

CodePudding user response:

If i understood the question correctly, you'll want to replace

        $newArray[$value['Number']]= $value['Number']." "."&pound;".$value['Cost'] / 100;

with

        $priceLabel = ($value['Number'] == 0 ? 'Free' : $value['Number'] . " &pound;");
        $newArray[( $value['Number'] )] = $priceLabel . ($value['Cost'] / 100);
  • Related