Home > Blockchain >  how to Addition with a number all column in php array
how to Addition with a number all column in php array

Time:01-14

hi i have a json file like this :

    "telegram": {
        "russia": {
            "price": "5000",
            "count": "✅ 7",
            "prefix": " 7"
        },"usa": {
            "price": "7000",
            "count": "✅ 9",
            "prefix": " 1"
        },
    },"google": {
        "russia": {
            "price": "5500",
            "count": "✅ 11",
            "prefix": " 7"
        },"usa": {
            "price": "7700",
            "count": "✅ 20",
            "prefix": " 1"
        },
    }

And I want to add all the available prices to a number like 200
how i can do it?

I do this ,But this is not working :

$services = json_decode(file_get_contents("myFile.json"), true);

foreach ($services as $service) foreach ($service as $country) {
    $country['price']  = 200;
    echo $country['price'] . '<br>';
}

echo '<br>' . json_encode($services);

The result :

5200
7200
5700
7900

"telegram": {
        "russia": {
            "price": "5000",
            "count": "✅ 7",
            "prefix": " 7"
        },"usa": {
            "price": "7000",
            "count": "✅ 9",
            "prefix": " 1"
        },
    },"google": {
        "russia": {
            "price": "5500",
            "count": "✅ 11",
            "prefix": " 7"
        },"usa": {
            "price": "7700",
            "count": "✅ 20",
            "prefix": " 1"
        },
    }

It shows the prices correctly when I echo inside foreach, but there is no change in the array

CodePudding user response:

Regarding to your comment. You miss one level loop and if you want to update the existing array, you need to pass by reference instead.

PS: unset is used in the example below because reference would be preserved after foreach and it need to be removed. Otherwise, if you use the same variable in other foreach, the reference may lead to unexpected behaviour.

<?php
$services = [
    'telegram' =>
    [
        'russia' => ['price' => '5000', 'count' => '7', 'prefix' => ' 7'],
        'usa' =>  ['price' => '7000', 'count' => '9',  'prefix' => ' 1'],
    ],
    'google' =>
    [
        'russia' => ['price' => '5500', 'count' => '11',  'prefix' => ' 7'],
        'usa' =>  ['price' => '7700', 'count' => '20', 'prefix' => ' 1'],
    ],
];

foreach ($services as &$countries) {
    foreach ($countries as &$country) {
        $country['price']  = 200;
        unset($country);
    }
    unset($countries);
}

print_r($services);
  •  Tags:  
  • Related