Alan Alan - 2 months ago 7
JSON Question

How to make the number from an array/ json_string negative

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!

Answer

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

foreach($array as $key => $number) {
   $array[$key] = 0 - $number;
}