如何使数组/ json_string中的数字为负数

时间:2016-09-16 08:35:03

标签: php arrays json

所以我有一个存储在名为$data的变量中的数组,如下所示:

["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)
      }

通过使用以下函数,我从数组中获取值:

                $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);

将它们存储到一个如下所示的json_string中:

[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]

我需要做的是我必须使非0号为负数。所以在这种情况下我想-1而不是1.任何想法如何实现这一点?谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

嗯,我发现它最原始的方法是:

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

答案 1 :(得分: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);

//来自@ Dmytrechko的代码