dtmjl4427 2014-04-18 12:58
浏览 18
已采纳

如何在php中使用foreach里面的数组?

I am trying to do foreach inside array. I am trying to generate the select box using array value everything seems ok when i give a value manually.

array(
    'name' => __('Testing Selection', 'test'),
    'id' => 'testing',
    'css' => 'min-width:150px;',
    'std' => '2', 
    'default' => '2',
    'type' => 'select',
    'options' => array(
        '1' => __('Test1', 'test'),
        '2' => __('Test2', 'test'),
        '3' => __('Test3', 'test'),
    ),
),

In the above code options key contains three values like 1, 2, 3 and the above code is working. But i want to loop all product id here using foreach but it seems not working for me may be i am trying a wrong way. I know foreach inside array is invalid that's why i am trying this way.

$foos = array(
    'name' => __('Testing Selection', 'test'),
    'id' => 'testing',
    'css' => 'min-width:150px;',
    'std' => '2', 
    'default' => '2',
    'type' => 'select',
    'options' => array(),
),

After array i did foreach

$args = array('post_type' => 'product', 'posts_per_page' => '-1');
$getproducts = get_posts($args);

foreach ($getproducts as $product) {
    $foos['options'][] = array(
        $product->ID => $product->get_title,
    );
}

I want to list 20 more products in the select box everything manually is hard to me can anyone suggest me to use the foreach inside array?

  • 写回答

3条回答 默认 最新

  • doufen2769 2014-04-26 17:21
    关注

    With PHP functions like array_map() or array_reduce() you can create the new array inside an array. array_map () is useful for creating the values ​​for an array, but you can not manipulate the keys with it. Because of that we can use array_reduce() to simulate the behavior of array_map() and to create the associative array needed for options.

    $foos = array(
        'name'      => 'Testing Selection',
        'id'        => 'testing',
        'css'       => 'min-width:150px;',
        'std'       => '2', 
        'default'   => '2',
        'type'      => 'select',
        'options'   => array_reduce( get_posts( 'post_type=product&posts_per_page=-1' ), function( $result, $item ) { 
            $result[$item->ID] = $item->post_title;
            return $result;
        })
    );
    

    If you don't like the approach, you can create new function that will return the required array for options, and thus improve the readability of code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。