【问题标题】:Extract [cat_ID] from array PHP从数组 PHP 中提取 [cat_ID]
【发布时间】:2014-06-24 06:56:13
【问题描述】:

我有以下数组(只是完整数组的一部分),我想提取 [cat_ID] 的值。

Array ([1] => stdClass Object ( [term_id] => 21 [name] => z_aflyst [slug] => z_aflyst
[term_group] => 0 [term_taxonomy_id] => 23 [taxonomy] => category 
[description] => [parent] => 0 [count] => 1 [object_id] => 7 [cat_ID] => 21 
[cat_name] => z_aflyst ))

所以在这种情况下我需要提取 21。但是,如果cat_name 等于z_aflyst,我只想提取cat_ID

【问题讨论】:

标签: php arrays wordpress


【解决方案1】:

假设你有一个对象数组:

Array (
[1] => stdClass Object 
( 
[term_id] => 21 
[name] => z_aflyst 
[slug] => z_aflyst
[term_group] => 0 
[term_taxonomy_id] => 23 
[taxonomy] => category 
[description] => 
[parent] => 0 
[count] => 1 
[object_id] => 7 
[cat_ID] => 21 
[cat_name] => z_aflyst )
)

foreach ($items as $item)
{
    if($item->cat_name == 'z_aflyst')
    {
        //do stuff
    }
}

【讨论】:

  • $items 是从哪里来的?
  • 您已经 var_dump 编辑了一个包含 stdClass 对象(当前为 1 个对象)的数组,我可以看到它......没有提供代码......
  • 他假设 $items=array(..your array..);
  • 你不需要 foreach.. 这将遍历所有元素而无需这样做
  • @Elzo Valugi:为什么?他有一个对象数组。
【解决方案2】:

您有一个standard objects 数组,可以使用箭头(对象)运算符-> 访问这些属性。

您可以使用array_filter() 过滤掉数组中不需要的元素:

// Assuming your array is called $items
$filtered = array_filter($items, function($v) {
    return $v->cat_name === 'z_aflyst';
});

之后,您可以使用 array_map() 将数组“展平”,使其仅包含 cat_ID(如果您愿意):

$filtered = array_map(function($v) {
    return $v->cat_ID;
}, $filtered);

这将为您留下一个 cat_ID 的一维索引数组。

【讨论】:

    【解决方案3】:

    在此示例中,您的数组不仅仅是一个简单的数组,而是一个standard object。您可以利用这一点。您可以通过以下公式获得标准对象的属性:

    $object->property;
    

    在你的情况下,对象是

    $object = $array[1];
    

    或者通过这个公式作为一个数组

    $array[key];
    

    在您的情况下获取 cat_ID 的值:

    $object->cat_ID;
    

    所以你的代码会是这样的:

    if ($object->cat_name == 'z_aflyst') {
         // do stuff with your cat_ID value
         echo $object->cat_ID;
    }
    // will echo 21 only of the cat_name has value 'z_aflyst'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      相关资源
      最近更新 更多