Я пробовал всевозможные решения, и никто, кажется, не делает то, что мне нужно, или я не понимаю, как их преобразовать для решения моей конкретной проблемы. В принципе, я возвращаю ряд строк с моего SQL-сервера. Запрос выглядит так:
$params = array(&$search, &$search, &$search, &$search, &$search, &$search, &$search, &$search); $tsql = "SELECT Item.ID, Item.ItemLookupCode, nitroasl_pamtable.ManufacturerPartNumber, SupplierList.ReorderNumber, Item.Notes, Item.Description, Item.ExtendedDescription, Item.Quantity, nitroasl_pamtable.SpoofStock, Item.Price, nitroasl_pamtable.PAM_Keywords, Item.PictureName FROM Item INNER JOIN nitroasl_pamtable ON Item.ID = nitroasl_pamtable.ItemID INNER JOIN SupplierList ON Item.ID = SupplierList.ItemID WHERE (Item.ItemLookupCode LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1) OR (Item.ID LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1) OR (nitroasl_pamtable.ManufacturerPartNumber LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1) OR (SupplierList.ReorderNumber LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1) OR (Item.Notes LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1) OR (Item.Description LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1) OR (Item.ExtendedDescription LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1) OR (nitroasl_pamtable.PAM_Keywords LIKE '%' + ? + '%' AND Price > 0.00 AND WebItem = 1)"; // Allows us to determine the number of rows returned $cursorType = array('Scrollable' => SQLSRV_CURSOR_KEYSET); $getProducts = sqlsrv_query($conn, $tsql, $params, $cursorType);
Затем я использую следующее, чтобы поместить строки в массив:
// Put results into an array while( $row = sqlsrv_fetch_array( $getProducts, SQLSRV_FETCH_ASSOC)) { $results['results'][] = $row; }
$ results ['results'] выглядит так, когда я ищу « tp-ac1750 (удалены некоторые возвращенные столбцы для более удобного просмотра):
Array ( [results] => Array ( [0] => Array ( [ItemLookupCode] => TP-AC1750 [ReorderNumber] => ARCHERC7 ) [1] => Array ( [ItemLookupCode] => TP-AC1750 [ReorderNumber] => N82E16833704177 ) [2] => Array ( [ItemLookupCode] => TP-AC1750 [ReorderNumber] => 7681617 ) [3] => Array ( [ItemLookupCode] => TP-AC1750 [ReorderNumber] => ARCHERC7 ) ) [keywords] => tp-ac1750 )
Я бы хотел, чтобы массив выглядел так:
Array ( [results] => Array ( [0] => Array ( [ItemLookupCode] => TP-AC1750 [ReorderNumber] => Array ( [0] => ARCHERC7 [1] => N82E16833704177 [2] => 7681617 ) ) ) )
Я пытался:
Но я не могу понять. Вот что я сейчас пытаюсь сделать:
// Remove duplicates $results['results'] = merge_duplicates( $results['results'] ); //*********************************************** // Merge duplicate arrays and their values //*********************************************** function merge_duplicates( $array ) { // Build temporary array for array_unique $tmp = array(); foreach( $array as $key => $value ) { $tmp[ $key ] = $value; } // Find duplicates in temporary array $tmp = array_unique( $tmp, SORT_REGULAR ); // Remove duplicates from original array foreach( $array as $key => $value ) { if ( !array_key_exists( $key, $tmp ) ) { unset( $array[ $key ] ); } } return $array; }
Есть ли способ выполнить этот тип слияния? Есть ли способ объединить эти дубликаты во время SQL-запроса? Любой совет будет принят во внимание! Заранее спасибо 🙂
Вот фактический массив, в котором я должен использовать это слияние (я все еще хочу использовать ItemLookupCode в качестве уникального ключа, но объединить все другие родственные ключи):
Array ( [0] => Array ( [ID] => 8265 [ItemLookupCode] => TP-AC1750 [ManufacturerPartNumber] => Archer C7 [ReorderNumber] => ARCHERC7 [Notes] => TP-LINK Archer C7 AC1750 Routr [Description] => TP-LINK Archer C7 AC1750 Routr [ExtendedDescription] => TP-Link Archer C7 Wireless-AC1750 Dual-Band Gigabit Router [Quantity] => 0 [SpoofStock] => [Price] => 129.9500 [PAM_Keywords] => [PictureName] => tp-ac1750.jpg ) [1] => Array ( [ID] => 8265 [ItemLookupCode] => TP-AC1750 [ManufacturerPartNumber] => Archer C7 [ReorderNumber] => N82E16833704177 [Notes] => TP-LINK Archer C7 AC1750 Routr [Description] => TP-LINK Archer C7 AC1750 Routr [ExtendedDescription] => TP-Link Archer C7 Wireless-AC1750 Dual-Band Gigabit Router [Quantity] => 0 [SpoofStock] => [Price] => 129.9500 [PAM_Keywords] => [PictureName] => tp-ac1750.jpg ) [2] => Array ( [ID] => 8265 [ItemLookupCode] => TP-AC1750 [ManufacturerPartNumber] => Archer C7 [ReorderNumber] => 7681617 [Notes] => TP-LINK Archer C7 AC1750 Routr [Description] => TP-LINK Archer C7 AC1750 Routr [ExtendedDescription] => TP-Link Archer C7 Wireless-AC1750 Dual-Band Gigabit Router [Quantity] => 0 [SpoofStock] => [Price] => 129.9500 [PAM_Keywords] => [PictureName] => tp-ac1750.jpg ) [3] => Array ( [ID] => 8265 [ItemLookupCode] => TP-AC1750 [ManufacturerPartNumber] => Archer C7 [ReorderNumber] => ARCHERC7 [Notes] => TP-LINK Archer C7 AC1750 Routr [Description] => TP-LINK Archer C7 AC1750 Routr [ExtendedDescription] => TP-Link Archer C7 Wireless-AC1750 Dual-Band Gigabit Router [Quantity] => 0 [SpoofStock] => [Price] => 129.9500 [PAM_Keywords] => [PictureName] => tp-ac1750.jpg ) )
Самый быстрый способ, о котором я могу думать:
<?php $results = array( array('ItemLookupCode' => 'name1', 'ReorderNumber' => 1), array('ItemLookupCode' => 'name1', 'ReorderNumber' => 2), array('ItemLookupCode' => 'name1', 'ReorderNumber' => 3), array('ItemLookupCode' => 'name1', 'ReorderNumber' => 2), array('ItemLookupCode' => 'name2', 'ReorderNumber' => 1), array('ItemLookupCode' => 'name2', 'ReorderNumber' => 1), ); function group($main, $item) { if(!isset($main[$item['ItemLookupCode']])) { $main[$item['ItemLookupCode']] = array('ReorderNumber' => array()); } if(!in_array($item['ReorderNumber'], $main[$item['ItemLookupCode']]['ReorderNumber'])) { $main[$item['ItemLookupCode']]['ReorderNumber'][] = $item['ReorderNumber']; } return $main; } $formatted_result = array(); foreach(array_reduce($results, "group") as $name => $item) { $formatted_result[] = array( 'ItemLookupCode' => $name, 'ReorderNumber' => $item ); } print_r($formatted_result);