Foreach循环和多维数组

时间:2014-11-19 03:39:23

标签: php

这是输出的多维数组的示例。

Array
(
    [0] => stdClass Object
        (
            [term_id] => 34
            [name] => ACS Consultants
            [slug] => acs-consultants
            [term_group] => 0
            [term_taxonomy_id] => 34
            [taxonomy] => ad_cat
            [description] => 
            [parent] => 0
            [count] => 0
            [cat_ID] => 34
            [category_count] => 0
            [category_description] => 
            [cat_name] => ACS Consultants
            [category_nicename] => acs-consultants
            [category_parent] => 0
        )

    [1] => stdClass Object
        (
            [term_id] => 18
            [name] => Business Development
            [slug] => business-development
            [term_group] => 0
            [term_taxonomy_id] => 18
            [taxonomy] => ad_cat
            [description] => 
            [parent] => 0
            [count] => 0
            [cat_ID] => 18
            [category_count] => 0
            [category_description] => 
            [cat_name] => Business Development
            [category_nicename] => business-development
            [category_parent] => 0
        )

    [2] => stdClass Object
        (
            [term_id] => 12
            [name] => Cash In Transit
            [slug] => cash-in-transit
            [term_group] => 0
            [term_taxonomy_id] => 12
            [taxonomy] => ad_cat
            [description] => 
            [parent] => 0
            [count] => 0
            [cat_ID] => 12
            [category_count] => 0
            [category_description] => 
            [cat_name] => Cash In Transit
            [category_nicename] => cash-in-transit
            [category_parent] => 0
        )
)

我尝试做的是将namecat_ID带入这样的新数组

$newarray['ACS Consultants']=34;
$newarray['Business Development']=18;
$newarray['Cash In Transit']=12;

这是我的尝试,但没有成功

$categories = get_categories( $args );

$newarray = array();


foreach($categories as $array) {
    foreach($array as $key=>$value) {
        if($key=="name") {
        $term = $key;
        $newarray[$term]="";
        }

        if($key=="cat_ID") {
        $newarray[$term]=$value;
        }
    }
}

我如何做到这一点?

2 个答案:

答案 0 :(得分:2)

它只是一个对象数组,你只需要一个循环。并使用->

访问对象
foreach ($categories as $category) {
    $newArray[$category->name] = $category->cat_ID;
}

答案 1 :(得分:0)

不需要第二个foreach循环,这应该这样做

$newArray = array();

foreach($categories as $array)
{
  $newArray[$array['name']] = $array['cat_ID'];
}
var_dump($newArray);

输出

array(3) {
  ["ACS Consultants"]=>string(2) "34"
  ["Business Development"]=>string(2) "18"
  ["Cash In Transit"]=>string(2) "12"
}

虽然我确实将$categories设置为一组数组进行测试,但如果namecat_ID是属性,则可能需要尝试以下操作

$newArray = array();

foreach($categories as $array)
{
  $newArray[$array->name] = $array->cat_ID;
}
var_dump($newArray);
相关问题