[英]How to add keys and values to an array the simplest way
I would like to know the simplest way to add the value of the $titles->post_title to become the key and value of an array.我想知道最简单的方法是将$titles->post_title 的值相加成为数组的键和值。
Here is my code:这是我的代码:
$data_from_database = array();
$titles = get_posts( array(
'post_type' => 'resort',
'order' => 'ASC'
) );
foreach($data_from_database as $field_key => $field_value) {
$field['choices'][$field_key] = $field_value;
$field['choices'][$field_value] = $field_value;
}
Desired result:想要的结果:
$data_from_database = array('1value' => '1value', '2value' => '2value',
'3value' => '3value');
I have looked and read other posts about this but wasnt able to find any info to achieved what i want to do.我已经查看并阅读了关于此的其他帖子,但无法找到任何信息来实现我想要做的事情。
Thanks for your answers in advance感谢您提前回答
Your question is completely unclear so try to add more details to get more complete answers.However based on you desired output您的问题完全不清楚,因此请尝试添加更多详细信息以获得更完整的答案。但是根据您所需的输出
$data_from_database = array('1value' => '1value', '2value' => '2value', '3value' => '3value');
and this:和这个:
I would like to know the simplest way to add the value of the $titles->post_title to become the key and value of an array.
我想知道最简单的方法是将$titles->post_title 的值相加成为数组的键和值。
you can alter your code to look like this:您可以将代码更改为如下所示:
$data_from_database = array();
$titles = get_posts( array(
'post_type' => 'resort',
'order' => 'ASC'
) );
foreach($titles as $field_key => $field_value) {
$data_from_database[$field_key] = $field_key;
}
Try this code to get your desired output试试这个代码来获得你想要的输出
$data_from_database = array();
$titles = get_posts( array(
'post_type' => 'news',
'order' => 'ASC'
) );
foreach($titles as $value) {
$data_from_database[$value->post_title] = $value->post_title;
}
Hope this helps you.希望这对你有帮助。
Thanks for the answers guys..谢谢各位大佬解答。。
I figured it out by using this code.我通过使用此代码弄清楚了。
$data_from_database = array();
$myarray = array();
$titles = get_posts( array( 'post_type' => 'resort') );
$new_title = wp_list_pluck($titles, 'post_title', 'post_title');
// reset choices
$field['choices'] = array();
// if has rows
foreach($new_title as $field_key => $field_value) {
$field['choices'][$field_key] = $field_value;
}
// return the field
return $field;
wordpress has a built in function to automatically push values and keys to an array wordpress 有一个内置函数可以自动将值和键推送到数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.