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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?