将30个键从数组保存到另一个变量

时间:2016-09-08 06:36:10

标签: php arrays highcharts

我的代码很遗憾。所以我有一个数组,大约有100个密钥保存在$ data变量中,如下所示:

["data"]=>
  array(413) {
    [0]=>
    object(stdClass)#254 (7) {
      ["Date"]=>
      string(10) "2016-09-08"
      ["Open"]=>
      string(6) "771.00"
      ["Close"]=>
      string(6) "782.00"
    }
    [1]=>
    object(stdClass)#254 (7) {
      ["Date"]=>
      string(10) "2016-09-07"
      ["Open"]=>
      string(6) "71.00"
      ["Close"]=>
      string(6) "82.00"
    }
    [2]=>
    object(stdClass)#254 (7) {
      ["Date"]=>
      string(10) "2016-09-06"
      ["Open"]=>
      string(6) "571.00"
      ["Close"]=>
      string(6) "682.00"
    }
    [3]=>
    object(stdClass)#254 (7) {
      ["Date"]=>
      string(10) "2016-09-05"
      ["Open"]=>
      string(6) "781.00"
      ["Close"]=>
      string(6) "702.00"
    }
  }

我尝试保存前30个["Close"]键,但我需要将它们从第30个键保存到第一个键,因此我的for循环:

<?php

     $lowValue = [];
     for($i = 29; $i >= 0; $i--){
        foreach ($data->data[$i] as $obj) {
          if (isset($obj->Close)) {
             return $lowValue[] = $obj->Close;
          }
        }
     }

 ?>
 data: {!! json_encode(lowValue) !!}

我需要使用json_encode保存的结果因为我将它用作高图的数据。但我得到一个空变量,任何想法为什么?我在互联网上查找的另一个问题,但我没有答案,我可以使用json_encode吗?这意味着如果我想创建一个函数,我可以将其用作参数吗?非常感谢您的时间,欢迎任何帮助! 在我修改了代码之后: 数据:

                  <?php
                    $lowValue = [];
                    foreach ($data->data as $obj) {
                        if (isset($obj->Close)) {
                            // add the element to the beginning of the array
                            array_unshift($lowValue, $obj->Close);
                        }

                        if(count($lowValue) >= 30) {
                            break;
                        }
                    }
                    echo json_encode($lowValue);
        ?>

2 个答案:

答案 0 :(得分:1)

请试试这个:

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

    if(count($lowValue) >= 30) {
        break;
    }
}

echo json_encode(['data' => $lowValue]);

关于你的第二个问题,你应该在SO上创建另一个问题。

答案 1 :(得分:0)

在@mapek的帮助下,在我对他的例子做了一些工作后,我的案例中的解决方案是:

data:<?php
       $lowValue = [];
       foreach ($data->data as $obj) {
          if (isset($obj->Close)) {
              // add the element to the beginning of the array
              array_unshift($lowValue, $obj->Close);
          }

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

显示我的数组如下:data:[621, 512, 578] ...