1

So I have an array stored in a variable called $data that looks like this:

["data"]=>
    ["rows"]=>
    array(30) {
      [0]=>
      array(3) {
        [0]=>
        string(10) "2016-08-15"
        [1]=>
        int(0)
        [2]=>
        int(0)
      }
      [1]=>
      array(3) {
        [0]=>
        string(10) "2016-08-16"
        [1]=>
        int(0)
        [2]=>
        int(0)
      }
      [2]=>
      array(3) {
        [0]=>
        string(10) "2016-08-17"
        [1]=>
        int(0)
        [2]=>
        int(0)
      }
      [3]=>
      array(3) {
        [0]=>
        string(10) "2016-08-18"
        [1]=>
        int(0)
        [2]=>
        int(0)
      }

By using the following function I take the values from the array:

                $subscribersGained = [];
                foreach ($data->data->rows as $obj) {
                    if (isset($obj[1])) {
                        // add the element to the beginning of the array
                        array_unshift($subscribersGained, $obj[1]);
                    }

                    if(count($subscribersGained) >= 30) {
                        break;
                    }
                }
                $gained = array_map( create_function('$value', 'return (int)$value;'),
                    $subscribersGained);
                echo json_encode($gained);

And store them into a json_string that looks like this:

[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

What I need to do is that I have to make the non 0 number be negative. So in this case I want to have -1 not 1. Any ideas how to make that happen? Thank you for your time!

Alan
  • 213
  • 1
  • 13
  • 1
    Any positive numbers you want to make negative you can just multiply by -1 to make them negative. – Jonnix Sep 16 '16 at 08:38

2 Answers2

1

Well, the most primitive way to do it that I figure out it is:

foreach($array as $key => $number) {
   $array[$key] = 0 - $number;
}
Dmytrechko
  • 598
  • 3
  • 11
1
$gained = array(0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

$gained = array_map(function($el) { return 0-$el; }, $gained);

print_r($gained);

//from @Dmytrechko`s code

CatalinB
  • 571
  • 4
  • 11