2014-11-14 111 views
0

我使用下面的代码片断在一个数组中返回第一个网址...返回第一个项目从阵列和一个其他随机项目

<?php 

$custom_field = get_post_meta($post->ID, '_images', true); 

foreach ($custom_field["docs"] as $custom_fields) { 
    $url1 = $custom_fields["imgurl"]; 
    echo $url1; 
    break; 
} 

?> 

我现在需要做的是创造另一个变量名为$ URL2这是来自阵列其余部分的随机图像。

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

任何图像也有类似的例子,我可以看看?

回答

1

这完全工作没有一个循环:

<?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"]; 
    } 
?> 
+0

感谢您的,意味着我可以摆脱循环,这有助于以及 – fightstarr20 2014-11-14 13:37:06

+0

此随机不会产生因某种原因URL2 $的。我看不到任何模式,每次都会生成$ url1。有任何想法吗? – fightstarr20 2014-11-14 13:57:15

+0

嗯,我不能保证你的数组每次都包含多于一个图像。你确定它总是被填满吗? – Steini 2014-11-14 13:58:16

1

您可以使用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()刚刚获得的第一个元素,它不会删除它。然后第二个操作,它从数组的第二个到最后一个得到一个随机键,所以第一个元素不包含在随机化中。

相关问题