[英]How can I limit the amount of array items
我有以下代碼部分:
private function get_shortcodes() {
$shortcodes = array();
$shortcodes += array_fill_keys( array( 'WPBUSDIRMANADDLISTING',
'businessdirectory-submitlisting' ),
array( &$this->controller, 'submit_listing' ) );
$shortcodes += array_fill_keys( array( 'WPBUSDIRMANMANAGELISTING',
'businessdirectory-managelistings',
'businessdirectory-manage_listings' ),
array( &$this->controller, 'manage_listings' ) );
$shortcodes += array_fill_keys( array( 'WPBUSDIRMANVIEWLISTINGS',
'WPBUSDIRMANMVIEWLISTINGS',
'businessdirectory-view_listings',
'businessdirectory-viewlistings',
'businessdirectory-listings' ),
array( &$this, '_listings_shortcode' ) );
$shortcodes += array_fill_keys( array( 'WPBUSDIRMANUI',
'businessdirectory',
'business-directory' ),
array( &$this->controller, 'dispatch' ) );
$shortcodes += array_fill_keys( array( 'businessdirectory-search',
'businessdirectory_search' ),
array( &$this->controller, 'search' ) );
$shortcodes['businessdirectory-featuredlistings'] = array( &$this, '_featured_listings_shortcode' );
return apply_filters( 'wpbdp_shortcodes', $shortcodes );
}
哪里...
$shortcodes += array_fill_keys( array( 'WPBUSDIRMANVIEWLISTINGS',
'WPBUSDIRMANMVIEWLISTINGS',
'businessdirectory-view_listings',
'businessdirectory-viewlistings',
'businessdirectory-listings' ),
array( &$this, '_listings_shortcode' ) );
...應該在我的網站上顯示一些目錄列表。 有用。 但它會根據插件設置檢索10個列表。 我只需要檢索2。換句話說,我需要限制它。
我試過使用array_slice
和array_splice array_unique
只檢索一些值,但是沒有用。
我究竟做錯了什么?
對於示例,我嘗試這樣使用它:
array_slice( ( &$this, '_listings_shortcode' ),0,2)
沒辦法
編輯
仍在嘗試...
if (!in_array('WPBUSDIRMANMVIEWLISTINGS', $shortcodes)){
if(count($shortcodes)>=2)
array_shift($shortcodes);
$shortcodes[] = 'WPBUSDIRMANMVIEWLISTINGS';
}
編輯2
好吧,通過php手動邏輯,它是正確的,但是仍然無法正常工作,雖然沒有出現任何錯誤,但是我嘗試了以下兩種方法:
這個
if (!in_array('_listings_shortcode', $shortcodes)){
if(count($shortcodes)>=1)
array_shift($shortcodes);
$shortcodes[] = ('_listings_shortcode');
}
和這個
if (!in_array('_listings_shortcode', $shortcodes)){
$count = count($shortcodes);
if($count>=1)
array_shift($shortcodes);
$shortcodes[] = ('_listings_shortcode');
}
您可以通過獲取數組長度以及長度小於或等於所需的amout並將元素添加到數組的末尾來實現。
這是執行此操作的簡單示例,我不知道這是否是您想要的... :)
if (!in_array($ExpectedArray, $yourArray)){
if(count($yourArray)>=2)
array_shift($yourArray);
$yourArray[] = $ExpectedArray;
}
欲了解更多信息: $ExpectedArray
不是一個數組 ,這是你期望的值$yourArray
請檢查該約in_array例子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.