Ho un array in cui voglio cercare il uid
e ottenere la chiave dell'array.
Supponiamo di avere il seguente array bidimensionale:
$userdb = array(
array(
'uid' => '100',
'name' => 'Sandra Shush',
'pic_square' => 'urlof100'
),
array(
'uid' => '5465',
'name' => 'Stefanie Mcmohn',
'pic_square' => 'urlof100'
),
array(
'uid' => '40489',
'name' => 'Michael',
'pic_square' => 'urlof40489'
)
);
La chiamata alla funzione search_by_uid(100)
(uid del primo utente) dovrebbe restituire 0
.
La chiamata di funzione search_by_uid(40489)
dovrebbe restituire 2
.
Ho provato a fare dei cicli, ma voglio un codice di esecuzione più veloce.
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
Questo funzionerà. Dovresti chiamarlo così:
$id = searchForId('100', $userdb);
È importante sapere che se stai usando l'operatore ===
i tipi confrontati devono essere esattamente gli stessi, in questo esempio devi cercare stringa
o semplicemente usare ==
invece di ===
.
Basato su angoru risposta. Nelle versioni successive di PHP (>= 5.5.0
) puoi usare il one-liner.
$key = array_search('100', array_column($userdb, 'uid'));
Ecco la documentazione: http://php.net/manual/en/function.array-column.php.
Basandosi su Jakub ottima risposta, ecco una ricerca più generalizzata che permetterà di specificare la chiave (non solo per uid):
function searcharray($value, $key, $array) {
foreach ($array as $k => $val) {
if ($val[$key] == $value) {
return $k;
}
}
return null;
}
Uso: $results = searcharray('searchvalue', searchkey, $array);
So che questo è già stato risposto, ma ho usato questo e l'ho esteso un po' di più nel mio codice in modo da non avere la ricerca solo per l'uid. Voglio solo condividerlo per chiunque altro possa avere bisogno di questa funzionalità.
Ecco il mio esempio e per favore tieni a mente che questa è la mia prima risposta. Ho tolto l'array di param perché avevo solo bisogno di cercare un array specifico, ma potresti facilmente aggiungerlo. Volevo essenzialmente cercare per più di un semplice uid.
Inoltre, nella mia situazione ci potrebbero essere più chiavi da restituire come risultato della ricerca per altri campi che potrebbero non essere unici.
/**
* @param array multidimensional
* @param string value to search for, ie a specific field name like name_first
* @param string associative key to find it in, ie field_name
*
* @return array keys.
*/
function search_revisions($dataArray, $search_value, $key_to_search) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
$keys[] = $key;
}
}
return $keys;
}
Più tardi, ho finito per scrivere questo per permettermi di cercare un altro valore e una chiave associativa. Quindi il mio primo esempio vi permette di cercare un valore in qualsiasi chiave associativa specifica, e restituire tutte le corrispondenze.
Questo secondo esempio vi mostra dove un valore ('Taylor') si trova in una certa chiave associativa (first_name) E un altro valore (true) si trova in un'altra chiave associativa (employed), e restituisce tutte le corrispondenze (chiavi dove le persone con nome 'Taylor' E sono occupate).
/**
* @param array multidimensional
* @param string $search_value The value to search for, ie a specific 'Taylor'
* @param string $key_to_search The associative key to find it in, ie first_name
* @param string $other_matching_key The associative key to find in the matches for employed
* @param string $other_matching_value The value to find in that matching associative key, ie true
*
* @return array keys, ie all the people with the first name 'Taylor' that are employed.
*/
function search_revisions($dataArray, $search_value, $key_to_search, $other_matching_value = null, $other_matching_key = null) {
// This function will search the revisions for a certain value
// related to the associative key you are looking for.
$keys = array();
foreach ($dataArray as $key => $cur_value) {
if ($cur_value[$key_to_search] == $search_value) {
if (isset($other_matching_key) && isset($other_matching_value)) {
if ($cur_value[$other_matching_key] == $other_matching_value) {
$keys[] = $key;
}
} else {
// I must keep in mind that some searches may have multiple
// matches and others would not, so leave it open with no continues.
$keys[] = $key;
}
}
}
return $keys;
}
Uso della funzione
$data = array(
array(
'cust_group' => 6,
'price' => 13.21,
'price_qty' => 5
),
array(
'cust_group' => 8,
'price' => 15.25,
'price_qty' => 4
),
array(
'cust_group' => 8,
'price' => 12.75,
'price_qty' => 10
)
);
$findKey = search_revisions($data,'8', 'cust_group', '10', 'price_qty');
print_r($findKey);
Risultato
Array ( [0] => 2 )