doushe2513 2018-08-09 16:14
浏览 146
已采纳

如何使用foreach重建用逗号分隔的一组数组?

I'm using ACF Pro to get all my choices or specific field. I want to store these choice values into an array structure like this...

$mstars = array( 
    'relation' => 'OR',
array (
    'key' => 'product_owner',
    'value' => 'Bob Ross',
    'compare' => 'LIKE'
),
array(
    'key' => 'product_owner',
    'value' => 'Michael Jackson',
    'compare' => 'LIKE'
),
array(
    'key' => 'product_owner',
    'value' => 'Tom Hanks',
    'compare' => 'LIKE'
)

...Bob, Micheal and Tom are the only things coming from my select choices. The 'key' and 'compare' can be manully placed in my loop sense that never changes. How should I go about building that? This is what I have so far...

//I'm getting the ACF key to find my specific field
$field_key = "field_5b5b34f4ed085";
//I now have field data
$field = get_field_object($field_key);

//initiate an array
$mstars = [];
//loop through all my choices of this specific field
foreach($field['choices'] as $mkey => $mvalue) {
    //how do I add 'key' => 'product_owner', to each sub array?
    //how can I add Bob, Michael and Tom as values to each sub array?
    //how do I add compare => 'LIKE' to each sub array?
}

//I could then use $mstars[] where needed for get_posts() arguments

Many thanks on how to do this!

A var_dump of my choices looks like this...

var_dump($field['choices']);

array(6) { 
  ["Michael Jackson"]=> string(16) "Michael Jackson" 
  ["Bob Ross"]=> string(12) "Bob Ross" 
  ["Tom Hanks"]=> string(13) "Tom Hanks"
}
  • 写回答

3条回答 默认 最新

  • dptdb84606 2018-08-09 16:26
    关注

    Assuming $mvalue is a string that contains the name you want:

    foreach($field['choices'] as $mkey=>$mvalue){
        $mstars[] = array(
         'key'=> 'product_owner',
         'value'=> $mvalue,
         'compare'=> 'LIKE'
        );
    }
    
    $mstars['relation'] = 'OR';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条