我感兴趣的是创建一个数组,其中每个项目都包含:
我正在使用一个ACF中继器的每一个帖子,持有许多图像,中继器的名称是carousel。
WP post对象与ACF字段之间没有联系。
这一问题:
嵌套foreach将所有图像推入第一篇文章中。
预期:
嵌套的foreach将只使用属于该post ID的图像填充$randomArray。
$workshop_posts_args = array(
'post_type' => 'workshops'
);
$randomArray = [
'post_id' => '',
'post_title' => '',
'post_image_url' => []
];
$post_query = new WP_Query($workshop_posts_args);
if ($post_query->have_posts()) {
while ($post_query->have_posts()) {
$post_query->the_post();
$carousel_array = get_field('carousel', get_the_ID());
echo "<h2>".get_the_title()."</h2>";
if ($carousel_array) {
foreach ($carousel_array as $carousel_images) {
foreach ($carousel_images as $image) {
$randomArray['post_id'] = get_the_ID();
$randomArray['post_title'] = get_the_title();
$randomArray['post_image_url'][] = $image['url'];
echo 'image_url:'.$image['url'].'<br>The array: <pre>'.print_r($randomArray, true).'</pre>';
?>
<?php
}
}
}
}
}
?>
<h1>TOTAL ARRAY</h1>
<pre><?php print_r($randomArray) ?></pre>发布于 2018-11-02 11:54:45
您在循环中一次又一次地重写数组索引,这就是您的问题。
也是:-
$randomArray = []; //before post_query并将if块更改如下:
if ($post_query->have_posts()) {
while ($post_query->have_posts()) {
$post_query->the_post();
$id = get_the_ID();
$randomArray[$id]['post_id'] = $id;
$randomArray[$id]['post_title'] = get_the_title();
$carousel_array = get_field('carousel', $id);
if ($carousel_array) {
foreach ($carousel_array as $carousel_images) {
foreach ($carousel_images as $image) {
$randomArray[$id]['post_image_url'][] = $image['url'];
?>
<?php
}
}
}
}
}注意:- rest代码将相同
以上代码将为您提供基于post-id的多维数组。如果你希望索引是0,1,2,3.然后做:-
$randomArray = array_values($randomArray);发布于 2018-11-02 11:53:47
使用适当的$randomArray索引如下:
<?php
$workshop_posts_args = array(
'post_type' => 'workshops'
);
$randomArray = array();
$post_query = new WP_Query($workshop_posts_args);
$index = 0;
if ($post_query->have_posts()) {
while ($post_query->have_posts()) {
$post_query->the_post();
$randomArray[$index]['post_id'] = get_the_ID();
$randomArray[$index]['post_title'] = get_the_title();
$carousel_array = get_field('carousel', get_the_ID());
//echo "<h2>".get_the_title()."</h2>";
if ($carousel_array) {
foreach ($carousel_array as $carousel_images) {
foreach ($carousel_images as $image) {
$randomArray[$index]['post_image_url'][] = $image['url'];
//echo 'image_url:'.$image['url'].'<br>The array: <pre>'.print_r($randomArray, true).'</pre>';
?>
<?php
}
}
}
$index++;
}
}
?>
<h1>TOTAL ARRAY</h1>
<pre><?php print_r($randomArray) ?></pre>https://stackoverflow.com/questions/53117947
复制相似问题