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条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题