我使用的是WordPress,它有一个定制的post类型设置,设置了一定数量的选项,基本分解如下:
我试图将所有的物品收集成一个分组的集合,以便与<optgroup />一起使用,以显示自助餐下的所有桌子,以及鸡尾酒下的所有桌子,如下所示:
诸若此类
我遇到的PHP问题是,我有一个包含所有类型(自助餐、鸡尾酒等)的主数组。以及一个(最初)名为tables的空数组元素,用于添加支持该特定类型的所有表。从ACF检索选项很好,从WordPress中检索单个帖子也很好,因此这是一个严格意义上的打包问题,可以作为JSON进行回放。下面是一个代码示例:
//gets the field associated with the different table types (Buffet, Cocktail, etc.)
$field = get_field_object('field_577ff065e6699');
$list = array();
//create the base array
foreach ($field["choices"] as $type) {
$list[] = array
(
"type" => $type, //Buffet, Cocktail, etc.
"tables" => array() //placeholder to add WP items
);
}
//now get all tables
$tablesQuery = new WP_Query( array( 'post_type' => 'table', 'posts_per_page' => -1, 'order' => 'ASC' ) );
//loop through and add the table(s) to their categories
while ( $tablesQuery->have_posts() ) : $tablesQuery->the_post();
//gets the types supported by this table
$tableTypes = get_field('options');
//individual types
foreach ($tableTypes as $tableType) {
//all types
foreach ($list as $supportedType) {
//see if there is a match and add it
if ($tableType == $supportedType["type"]) {
//add to the array since it matches
$table = array
(
"name" => get_the_title(),
"sqft" => (int)get_field('square_footage'),
"seats" => (int)get_field('seats')
);
array_push($supportedType["tables"], $table);
//shows the single table above, but nothing prior
print_r($supportedType);
}
}
}
endwhile;
wp_reset_postdata();
//all "tables" arrays are empty here
var_dump($list);上面print_r($supportedType)的输出最后显示了所有数据,但是当tables条目应该是多个时,它总是只有一个元素:
Array
(
[type] => Buffet
[tables] => Array
(
[0] => Array
(
[name] => 30” Round Bistro/Cocktail Table
[sqft] => 42
[seats] => 2
)
)
)
Array
(
[type] => Cake
[tables] => Array
(
[0] => Array
(
[name] => 30” Round Bistro/Cocktail Table
[sqft] => 42
[seats] => 2
)
)
)
[.. snip ..]最后,当我在最后执行var_dump($list)时,所有类型都会出现,但是它们关联的tables数组都是空的:
array(11) {
[0]=>
array(2) {
["type"]=>
string(6) "Buffet"
["tables"]=>
array(0) {
}
}
[1]=>
array(2) {
["type"]=>
string(4) "Cake"
["tables"]=>
array(0) {
}
}这让我彻底迷失了方向,尽管它必须是我所错过的一些极其基本的东西。知道为什么tables是空的,尽管在环项上使用了array_push吗?我也尝试过$supportedType["tables"][] = $table,但这也有同样的效果。
发布于 2017-08-02 21:05:17
我认为您正在处理这个foreach:foreach ($list as $supportedType) {中数组的副本
试着把它改成
foreach ($list as $key => $supportedType) {
...
// this operates on the copy
// array_push($supportedType["tables"], $table);
// operate on the original instead
array_push($list[$key]["tables"], $table);
...
}https://stackoverflow.com/questions/45470875
复制相似问题