【问题标题】:php array_slice cant find arrayphp array_slice 找不到数组
【发布时间】:2013-07-17 07:46:29
【问题描述】:

我正在通过其他人的脚本获取一些数据,这些脚本形成了我想要切片的数组,因为那里有很多旧数据,我只需要最新的最新数据。

我正在像这样从 xml 创建一个数组:

    $result = (object)$SOAP->Export($token, $exportCmd, $admin);

    if($result->response->code != APIResponse::Success)
      die("Failed to Export");

    $exportedXML = $result->exportResult;

    $xml = trim(str_replace("Content-type: text/xml", " ", $exportedXML));

    $xml = simplexml_load_string($xml);

    $json = json_encode($xml);

    $response = json_decode($json,TRUE);

如果我打印响应,我会得到如下信息:

Array ( 
[R2420] => Array ( 
[0] => Array ( [F2400] => 00200002 [F2425] => 01 [F2426] => 050 ) 
[1] => Array ( [F2001] => text [F2400] => 00200002 [F2425] => 00 [F2426] => 060 ) 
[2] => Array ( [F2001] => text [F2400] => 00200008 [F2425] => 01 [F2426] => 080 ) 
[3] => Array ( [F2001] => text [F2400] => 00200008 [F2425] => 02 [F2426] => 080 ) 
[4] => Array ( [F2001] => text [F2400] => 00200026 [F2425] => 00 [F2426] => 150 ) 
[5] => Array ( [F2400] => 00200038 [F2425] => 01 [F2426] => 330 )
)
)

这个到 5,实际到 2000 年左右。例如,我只想要最后 200 个。但是当我使用 $output = array_slice($response, -200, 200); 它不会切掉任何东西,我认为那是因为它是数组中的一个数组,但是怎么切片?

谢谢!

【问题讨论】:

  • 旁注:APIResponse::Success 建议您使用类常量。约定是常量名大写,类名和静态都是Ucfirst

标签: php slice


【解决方案1】:

你可以

$output = array_slice($response[0], -200, 200);

如果您确定它是您想要的数组中的第一个元素。

只需确保将其包装在 $response[0] 存在的检查中即可。

$output = false;
if (!empty($response[0]))
    $output = array_slice($response[0], -200, 200);

【讨论】:

    【解决方案2】:

    " 如果给定长度并且为负数,则序列将从数组末尾停止那么多元素。如果省略,则序列将包含从偏移量到数组末尾的所有内容。" - php .net

    所以你想做的很简单: $output = array_slice($response, -200);

    【讨论】:

    • 这并不能解决问题:OP 想要切片的数组位于 $response 数组中。 array_slice($foo,-200,200); 是完全有效的,虽然第三个参数有点矫枉过正
    • 是吗?据我了解,OP 想要对外部数组进行切片。
    • 看看 OP 问题中的示例响应,以及实际问题: "t wont slice 任何东西,我认为那是因为它是数组中的一个数组,但是我该如何切片那个?” -> 数组中的数组是他想要切片的
    【解决方案3】:

    简单,把你要切片的数组切片:

    $output = array_slice($repsonse['R2420'],-200);
    

    我假设您知道密钥 R2420。如果没有:

    $output = array_slice(reset($response), -200);
    

    您不必使用reset,当然:array_poparray_shiftend... 也可以。无论哪种方式都能最快(最简单)获得您想要拼接的阵列。
    如果要拼接所有子数组:

    $output = array();
    foreach($response as $part => $arr)
    {
        $output[$part] = array_slice($arr, -200);
    }
    

    PS:如果你想要最后200个索引,你不需要指定第三个参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-08
      • 2021-11-10
      • 2015-02-03
      • 2019-08-24
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多