简体   繁体   English

我如何只访问此PHP数组中的特定数组值

[英]how do I access only specific array values in this PHP array

I get this php array back from Apples APNS feedback service: 我从Apples APNS反馈服务处获得了这个php数组:

array(4) { 
    [0]=> string(64) "abc123" 
    [1]=> string(64) "def456"
    [2]=> array(3) { 
            ["timestamp"]=> int(1426717247) ["length"]=> int(32) ["devtoken"]=> string(64) "xyz987" 
    }
    [3]=> array(3) { 
            ["timestamp"]=> int(1426717247) ["length"]=> int(32) ["devtoken"]=> string(64) "xyz987" 
    }
}

How do I use php to loop over this array, and build a comma separated string of only the array elements that contain 'devtoken' item / value(s)? 如何使用php遍历此数组,并仅用包含'devtoken'项目/值的数组元素构建逗号分隔的字符串?

UPDATE: I had been trying to do it with implode, and that may be do-able, but what I ended up using was based on the answer from Steve and looks like the following: 更新:我一直在尝试内爆,但这可能是可行的,但是我最终使用的是基于史蒂夫的回答,如下所示:

$deldevidstring='';
foreach($feedback_tokens as $element){
    if(is_array($element) && isset($element['devtoken'])){
        $deldevidstring .= $element['devtoken'] .',' ;
    }
}
if(strlen(trim($deldevidstring)) > 0){
   echo trim("delete these... " . $deldevidstring, ',');
}

iterate the array and build your string: 迭代数组并构建您的字符串:

$string='';
foreach($array as $element){
    if(isset($element['devtoken'])){
        $string .=',' . $element['devtoken'];
    }
}
echo trim($string, ',');

Or implode a filtered array: 或内爆过滤数组:

$string = implode(',', 
              array_filter(
                  array_map(
                      function($element){
                          return $element['devtoken']
                      }, 
                      $array
                  )
              )
          );

Check this out: 看一下这个:

<?php

$str = "";

foreach($array as $arr)
{
    if(is_array($arr))
    {
        if(array_key_exists('devtoken', $arr))
        {
            $str = implode(",", $arr)."\n";
        }
    }
}

?>

Assuming you have set $records = the array you got back: 假设您设置了$ records =您返回的数组:

$string = '';

foreach ($records as $record) {
    if (isset($array['devtoken'])) {
        $string .= $array['devtoken'] . ', ';
    }
}
$string = substr($string, 0, -2);
echo $string;

There are no doubt more elegant ways to do this but for short and quick this seems to work. 毫无疑问,这是更优雅的方法,但总之,这似乎是可行的。

No need to loop. 无需循环。 With PHP >= 5.5.0: 使用PHP> = 5.5.0:

$result = implode(',', array_column($array, 'devtoken'));

For earlier versions without array_column : 对于没有array_column早期版本:

$result = implode(',', array_filter(array_map(function($v) { return $v['devtoken']; }, $array)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM