1

我有一个数组。这是该var_dump数组的。

array (size=2)
  0 => 
    object(stdClass)[266]
      public 'term_id' => string '4' (length=1)
      public 'name' => string 'Test' (length=4)
      public 'slug' => string 'test' (length=4)
      public 'term_group' => string '0' (length=1)
      public 'term_taxonomy_id' => string '4' (length=1)
      public 'taxonomy' => string 'filter' (length=6)
      public 'description' => string '' (length=0)
      public 'parent' => string '0' (length=1)
      public 'count' => string '0' (length=1)
  1 => 
    object(stdClass)[277]
      public 'term_id' => string '5' (length=1)
      public 'name' => string 'test2' (length=5)
      public 'slug' => string 'test2' (length=5)
      public 'term_group' => string '0' (length=1)
      public 'term_taxonomy_id' => string '5' (length=1)
      public 'taxonomy' => string 'filter' (length=6)
      public 'description' => string '' (length=0)
      public 'parent' => string '0' (length=1)
      public 'count' => string '0' (length=1)

现在我想像这样转换该数组。

$choices = array(
  array('label' => 'Test','value' => 'test'),
  array('label' => 'test2','value' => 'test2'),
)

请注意:我在choices数组中映射了这样的键

  name key as label
  slug key as value

有人可以告诉我如何实现这一目标吗?

更新:

这是我到目前为止所尝试的。

foreach ( $filters as $filter ) { 
$filterarr[] = "array('label' => '". $filter->name ."' ,'value' => '". $filter->slug ."' )"; 
} 
$choices = array($filterarr);

但它没有按预期工作。

4

4 回答 4

1

试试看

$choices = array();    
$tempArray = array();

for($i=0; $i < count(YOUR_ARRAY); $i++)
{
    $tempArray["label"] = array[$i]->name;
    $tempArray["value"] = array[$i]->slug;

    array_push($choices, $tempArray);
}
于 2013-03-07T17:30:52.590 回答
1

只需对您的对象进行类型转换。并执行您想要的操作,如下所示。

$posts = (array) $yourObject;
$choices = array();
foreach($posts as $post){
   $choices[]['label'] = $post['name'];
   $choices[]['value'] = $post['slug'];
}
于 2013-03-07T17:31:09.200 回答
0

你可以写这样的东西,但下次尝试自己找到它很简单。

foreach($your_array as $a)
{
    $choices[] = array('label' => $a['label'],
                       'value' => $a['slug']);
}
于 2013-03-07T17:30:45.643 回答
0

尝试;

foreach($array as $object){
   $choices[] = array("label" => $object->name, "value" => $object->slug);
}
于 2013-03-07T17:32:29.720 回答