2016-07-20 26 views
1

刪除值我有類從數據庫中獲取值的數組與數字從陣列中的PHP

<?php foreach ($category_1['children'] as $category_2) { ?> 
    <li><a href="<?php echo $category_2['href']; ?>"> 
<?php echo $category_2['name']; ?></a> 
<?php } ?> 

它返回像

8.5" x 14" (Tri-Fold) 8.5" x 2.75" 8.5" x 3.667" (1/3 Page) 8.5" x 5.5" 8.5" x 5.5" (1/2 Page) 80lb gloss book, 16 Page Wall Calendar 9" x 12" Envelope 9" x 14.5" Booklets/Catalogs Bookmarks Brochures Business Cards Calendars

問題值是,我要刪除其中包含數字的值並僅顯示名稱的值。 例如。

Booklets/Catalogs Bookmarks Brochures Business Cards Calendars

所以,我怎麼能刪除從數組號的值。可以將它與array_filter使用通配符來完成。

回答

3

使用array_filterpreg_match功能的解決方案:

... 

$category_1['children'] = array_filter($category_1['children'], function($v){ 
    return !preg_match("/\d/", $v["name"]); 
}); 
// now the $category_1['children'] array contains only items with needed "names" 
+0

感謝的人,它的工作就像一個魅力。 –

+0

@SamB,不客氣 – RomanPerekhrest

0

你是對的,array_filter()是解決方案。

$new_array = array_filder($category_1['children'], function ($element) { 
    return !preg_match("~[0-9]~", $element['name']) 
} 

我沒有測試它,但它應該工作。

做這個foreach()並用die(var_dump($new_array))校驗值;

//編輯 由@romanperekhrest提供的解決方案是一個更好的preg_match,無論如何,如果你不想使用正則表達式,另一種是

!strpbrk($element, '1234567890') 

這顯然意在裏面關閉

1

我測試了下面的代碼,它的工作原理。它通過循環使用數組for循環,當它發現一排的href這不是空的它會從數組的元素。您可以在下面看到,我創建了數組$category_1['children']

<?php 


$category_1['children'] = array(
    array('href' => 'j', 'name' => 'aa'), 
    array('href' => '', 'name' => 'bb'), 
    array('href' => 'j', 'name' => 'aa'), 
    array('href' => 'l', 'name' => 'aaas'), 
    array('href' => '', 'name' => 'aa'), 
    array('href' => '', 'name' => 'cc') 
); 

現在的時間來梳理出來:

$array = $category_1['children']; 
for ($i=0; $i < count($category_1['children']); $i++) { 
    if($category_1['children'][$i]['href'] != null) { 
    unset($category_1['children'][$i]); 
    } 
} 

驗證結果:

print_r($category_1['children']); 
0
<?php foreach ($category_1['children'] as $category_2) { 
     $str = $category_2['name']; 
     preg_match('!\d+!', $str, $matches); 
     if(empty($matches))){ 
     ?> 
     <li><a href="<?php echo $category_2['href']; ?>"><?php echo $category_2['name']; ?></a> 
    <?php } 
     }?> 

預浸匹配檢查類別名稱中的數字值,如果沒有數字數據,則顯示該列表。

0

下面是簡單的方法:

<?php foreach ($category_1['children'] as $category_2) { ?> 

<?php if(1 !== preg_match('~[0-9]~', $category_2['name'])){ ?> 

    <li><a href="<?php echo $category_2['href']; ?>"> 

     <?php echo $category_2['name']; ?></a></li> 

<?php } } ?> 
0

您可以簡單地使用正則表達式'/^[a-zA-Z ]*$/'並選中就可以了:如

<?php foreach ($category_1['children'] as $category_2) { 

    if(preg_match('/^[a-zA-Z ]*$/', category_2['name'])) {?> 

    <li><a href="<?php echo $category_2['href']; ?>"><?php echo $category_2['name']; ?></a></li> 

    <?php } 

} ?>