从数组中返回第一项和另一个随机项


Return first item from array and one other random item

我使用以下代码片段返回数组中的第一个 URL...

<?php
$custom_field = get_post_meta( $post->ID, '_images', true);
foreach ($custom_field["docs"] as $custom_fields) {
    $url1 = $custom_fields["imgurl"];
    echo $url1;
    break;
}
?>

我现在需要做的是创建另一个名为 $url 2 的变量,它是数组其余部分的随机图像。

我还需要确保它不会重新选择用于$url1的图像

有人有类似的例子我可以看吗?

这完全没有循环:

<?php
    $custom_field = get_post_meta( $post->ID, '_images', true );
    //Directly access first url in the array
    $url1 = $custom_field["docs"][0]["imgurl"];
    echo $url1;
    //Remove first element from array to avoid duplicate random entry
    unset($custom_field["docs"][0]); 
    if(count($custom_field["docs"]) > 0) {
        //Generate a random index from first entry (0) until the element count in array - 1 (Because first element is index 0 and elementcount starts with 1 at first element!)
        $randID = rand(0, count($custom_field["docs"]) - 1);
        //Use random generated number to get second element out of array...
        $url2 = $custom_field["docs"][$randID]["imgurl"];
    }
?>
在这种情况下,

您可以使用array_shift然后array_rand的组合:

$custom_field = get_post_meta($post->ID, '_images', true);
$first_url = array_shift($custom_field);
$second_url = $custom_field[array_rand($custom_field)];

因此,首先,array_shift()的角色取出第一个元素,然后将其转移到$first_url中。然后,array_rand()只获取在第二个分配中使用的随机密钥。

或者,如果您不希望该数组被触摸,(不希望从unset()/array_shift中取消设置/删除任何元素):

$custom_field = get_post_meta($post->ID, '_images', true);
$first_url = reset($custom_field); // get the first element
$second_url = $custom_field[array_rand(array_slice($custom_field, 1))];

reset()只获取第一个元素,不会删除它。然后第二个操作,它只是从数组的第二个到最后一个获得一个随机键,因此第一个元素不包括在随机化中。