2016-09-18 3 views
0

Я хочу удалить повторяющиеся значения из многомерного массива. У меня есть выходной массив как это: -Как удалить повторяющиеся значения из массива в PHP?

0 => 
    array (size=4) 
     'product_category' => string 'Apparel' (length=7) 
     'product_sub_cat' => string 'T-Shirts' (length=8) 
     'product_type' => string 'T-Shirts' (length=8) 
     'count' => int 14 
    1 => 
    array (size=4) 
     'product_category' => string 'Apparel' (length=7) 
     'product_sub_cat' => string 'Hoodies & Sweatshirts' (length=21) 
     'product_type' => string 'Hoodies & Sweatshirts' (length=21) 
     'count' => int 5 
    2 => 
    array (size=4) 
     'product_category' => string 'Apparel' (length=7) 
     'product_sub_cat' => string 'Sweaters' (length=8) 
     'product_type' => string 'Sweaters' (length=8) 
     'count' => int 1 
    3 => 
    array (size=4) 
     'product_category' => string 'Sports & Entertainment' (length=22) 
     'product_sub_cat' => string 'Team Sports' (length=11) 
     'product_type' => string 'Basketball' (length=10) 
     'count' => int 1 
    4 => 
    array (size=4) 
     'product_category' => string 'Sports & Entertainment' (length=22) 
     'product_sub_cat' => string 'Other Sports & Entertainment Products' (length=37) 
     'product_type' => string 'Other Sports & Entertainment Products' (length=37) 
     'count' => int 1 

Я хочу удалить Одежды и спорт & Entertainment, который показывает несколько раз. Я хочу удалить 'Product_category' повторяющиеся значения. Ниже мой код

$stmt = $pdo->prepare("SELECT `product_category`, `product_sub_cat`, `product_type` FROM `search` WHERE product_name LIKE {$string} 
       OR `product_type` like '%" . $keyword . "%' OR `product_sub_cat` like '%" . $keyword . "%' ORDER BY `product_type` 
       LIKE '%" . $keyword . "%' DESC, `product_name`LIKE '%" . $keyword . "%' DESC "); 
$stmt->execute(); 
$RelatedCategoryProduct = $stmt->fetchAll(PDO::FETCH_ASSOC); 

//------------------------------- Count and Remove Duplicate Related Category Array values ------------------------------ 

function unserialize_unique_count($input, $k = 'count') { 
    $a = []; 
    foreach ($input as $d) { 
     $s = serialize($d); 
     $a[$s] = (isset($a[$s]) ? ($a[$s] + 1) : 1); 
    } 
    foreach ($a as $s => $c) { 
     $a[$s] = unserialize($s) + [ $k => $c]; 
    } 
    return array_values($a); 
} 

$grouped_with_count = unserialize_unique_count($RelatedCategoryProduct); 

Выше кода только удаление дубликатов значений «PRODUCT_TYPE». Я также хочу удалить повторяющиеся значения 'product_category'. Заранее спасибо.

Редактировать

Я хочу привести, как это: -

0 => 
    array (size=4) 
     'product_category' => string 'Apparel' (length=7) 
     'product_sub_cat' => string 'T-Shirts' (length=8) 
     'product_type' => string 'T-Shirts' (length=8) 
     'count' => int 14 
    1 => 
    array (size=4) 

     'product_sub_cat' => string 'Hoodies & Sweatshirts' (length=21) 
     'product_type' => string 'Hoodies & Sweatshirts' (length=21) 
     'count' => int 5 
    2 => 
    array (size=4) 

     'product_sub_cat' => string 'Sweaters' (length=8) 
     'product_type' => string 'Sweaters' (length=8) 
     'count' => int 1 
    3 => 
    array (size=4) 
     'product_category' => string 'Sports & Entertainment' (length=22) 
     'product_sub_cat' => string 'Team Sports' (length=11) 
     'product_type' => string 'Basketball' (length=10) 
     'count' => int 1 
    4 => 
    array (size=4) 

     'product_sub_cat' => string 'Other Sports & Entertainment Products' (length=37) 
     'product_type' => string 'Other Sports & Entertainment Products' (length=37) 
     'count' => int 1 

Посмотрите на вид спереди конца ..

Please see the image for better understanding

+0

просто удалите 'product_category' из' SELECT' Query – Noman

+0

@Noman, но я хочу, чтобы 'product_category' отображался, но только 1 раз. Если я удалю 'product_category', то как это будет показано. Спасибо за ответ. –

+0

вам нужно установить условия в категории продукта. это самое простое решение :) – Noman

ответ

0

ли подсчет и группировка в SQL-запрос.

$stmt = $pdo->prepare(" 
    SELECT `product_category`, `product_sub_cat`, `product_type`, COUNT(*) as count 
    FROM `search` 
    WHERE product_name LIKE {$string} 
     OR `product_type` like '%" . $keyword . "%' OR `product_sub_cat` like '%" . $keyword . "%' 
    GROUP BY `product_category`, `product_sub_cat`, `product_type` 
    ORDER BY `product_type` LIKE '%" . $keyword . "%' DESC, `product_name`LIKE '%" . $keyword . "%' DESC "); 
+0

@Barmer все еще показывает' product_category' (** Apparel **) 3 раза, когда мой код выполняет заданный вопрос. Ничего не изменилось. Благодарю. –

+0

Но у него есть другая подкатегория или тип продукта каждый раз, не так ли? Это целая комбинация, которая будет уникальной. – Barmar

+0

Не могли бы вы показать, на что вы хотите, чтобы результат выглядел? – Barmar

0

Как я понимаю ваш вопрос, вы хотите напечатать категорию один раз, ниже код сделает это.

Код:

$category = []; 
$column = 'product_category'; 
foreach($array as $subarray) { 
    $i = 0; 
    foreach($subarray as $key => $val) { 
     if($key == $column && ! in_array($val, $category)) { 
      $category[] = $val; 
      echo "<h2>".$val."</h2>"; 
     } 
     else if($key != $column) { 
      echo '<br>'.$key.' : <b>'.$val.'</b>'; 
     } 
    } 
    echo '<br>'; 
} 

Выход:

category=>Apparel 


product_sub_cat : T-Shirts 
product_type : T-Shirts 
count : 14 

product_sub_cat : Hoodies & Sweatshirts 
product_type : Hoodies & Sweatshirts 
count : 5 

product_sub_cat : Sweaters 
product_type : Sweaters 
count : 1 
category=>Sports & Entertainment 


product_sub_cat : Team Sports 
product_type : Basketball 
count : 1 

product_sub_cat : Other Sports & Entertainment Products 
product_type : Other Sports & Entertainment Products 
count : 1 

Как вы можете видеть category=>Apparel и category=>Sports & Entertainment печать только один раз .. я добавил category=> для всего, например, вы можете изменить вывод по желанию. :)

Смежные вопросы