php - Find array for which a key have a given value - php

I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.

Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).

As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.

$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}

I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)

array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"

It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.

Related

PHP: Check for existing array inside of array of objects

Have a problem with checking array inside of large array of objects. For example I have
$arr1 = array("a"=>12,"b"=5,"c"=>16);
and I need to check if this array exists inside array like this:
$arr2 = array( array( "a"=>12,"b"=5,"c"=>16),
array("d"=>1,"g"=5,"c"=>16),
array("a"=>12,"c"=5,"e"=>3) );
I have tried in_array(), and it works, but takes a lot of time if I have large $arr2.
Thank you in advance.
P.S. works with PHP 5.6
Instead of your current $arr structure, you'd better have an associative array, where the keys uniquely identify the value.
If you need to search that array several times, you might still save time if you would spend some time to create such associative array from your existing array:
$arr2 = array(
array( "a"=>12,"b"=>5,"c"=>16),
array("d"=>1,"g"=>5,"c"=>16),
array("a"=>12,"c"=>5,"e"=>3)
);
// use key/value pairs, with as key the JSON-encoding of the value
// Note: this will take some time for very large arrays:
foreach ($arr2 as $sub) {
ksort($sub); // need to sort the keys to make sure we can find a match when needed
$hash[json_encode($sub)] = $sub;
}
// function to see whether the value is in the array: this will be fast!
function inHash($hash, $sub) {
ksort($sub);
return isset($hash[json_encode($sub)]);
}
// test
if (inHash($hash, array("d"=>1,"g"=>5,"c"=>16))) {
echo "found";
} else {
echo "not found";
}
Of course, if you could create the original immediately with such keys, then you don't have the overhead of creating it afterwards.
#D.Kurapin simply try with == or === operator(according to you) with foreach() like below:
<?php
$arr1 = array("a"=>12,"b"=>5,"c"=>16);
$arr2 = array( array( "a"=>12,"b"=>5,"c"=>16),
array("d"=>1,"g"=>5,"c"=>16),
array("a"=>12,"c"=>5,"e"=>3) );
$isExist = false;
foreach ($arr2 as $key => $value) {
if($value === $arr1){
$isExist = true;
break;
}
}
if($isExist){
echo "yes found in the array";
}
else{
echo "sorry did not find in the array";
}

PHP assoiative Array with almost Similar Keys

I have an associative array
array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
)
What i Want to do is catch all the array keys where the key name has similarities
for example
i want to echo out item_name (it should get both item_name1 & item_name2) but i require it in a loop (foreach/for) so that i can send within the loop the details to my database for each set of values
Thanks For the help
Use the funtion array_keys
$allKeys = array_keys($yourArray);
$amountKeys = count($allKeys);
Unless you do not provide more code this will give you all the keys of $yourArray
Reference - array_keys
To get all the similar keys you can use this function similar-text()
Since I do not know how "similar" a key can be I would suggest you to test out different values and find a degree that matches your expectations.
Your data model seems to use numeric suffixes as a replacement for arrays so I'll assume that key name has similarities is an overestimated problem statement and you merely want to fix that.
The obvious tool is regular expressions:
$original_data = array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
);
$redacted_data = array();
foreach ($original_data as $key => $row) {
if (preg_match('/^(.+)(\d+)$/u', $key, $matches)) {
$redacted_data[$matches[1]][$matches[2]] = $row;
} else {
$redacted_data[$key][] = $row;
}
}
var_dump($redacted_data);
It should be easy to tweak for your exact needs.
I can't figure out what the i require it in a loop (foreach/for) requirement means but you can loop the resulting array as any other array:
foreach ($redacted_data as $k => $v) {
foreach ($v as $kk => $vv) {
printf("(%s,%s) = %s\n", $k, $kk, $vv);
}
}
<?php
$items=[];
$itemsNumbers=[];
foreach($itemarr as $key=> $val)
{
$itempos = strpos("item_name", $key);
if ($pos !== false)
$items[]=$val;
$numberpos = strpos("item_number", $key);
if ($numberpos !== false)
$itemsNumbers[]=$val;
}
?>
Note: here $itemarr is your input array
$items you will get list of item names and $itemsNumbers you will get list of itemsNumbers

how to get the index of an array using the value in php

<?php
$interests[50] = array('fav_beverages' => "beer");
?>
now i need the index (i.e. 50 or whatever the index may be) from the value beer.
I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.
please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.
thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer");
$interests[50] = array('fav_cuisine' => "arabic");
$interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.
This should work in your case.
$interests[50] = array('fav_beverages' => "beer");
function multi_array_search($needle, $interests){
foreach($interests as $interest){
if (array_search($needle, $interest)){
return array_search($interest, $interests);
break;
}
}
}
echo multi_array_search("beer", $interests);
If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:
$needle = 'beer';
foreach ($interests as $index => $arr) {
foreach ($arr as $value) {
if ($value == $needle) {
echo $index;
break;
}
}
}
Demo

PHP - How to append array with some conditions

$list = array(
[0]=> array(
[name]=>'James'
[group]=>''
)
[1]=> array(
[name]=>'Bobby'
[group]=>''
)
)
I am looking to update the item 'group' where the name is 'Bobby'. I am looking for a solution with the two following formats. Thank you in advance for your replies. Cheers. Marc.
array_push($list, ???)
and
$list[] ??? = someting
As far as I know, there's no way updating your array with one of the given syntax.
The only similar thing I can come on is looping over the array using array_walk ... http://www.php.net/manual/en/function.array-walk.php
Example:
array_walk($list, function($val, $key) use(&$list){
if ($val['name'] == 'Bobby') {
// If you'd use $val['group'] here you'd just editing a copy :)
$list[$key]['group'] = "someting";
}
});
EDIT: Example is using anonymous functions which is only possible since PHP 5.3. Documentation offers also ways working with older PHP-versions.
This code may help you:
$listSize = count($list);
for( $i = 0; $i < $listSize; ++$i ) {
if( $list[$i]['name'] == 'Bobby' ) {
$list[$i]['group'] = 'Hai';
}
}
array_push() doesn't really relate to updating a value, it only adds another value to an array.
You cannot have a solution that will fit both formats. The implicit array push $var[] is a syntactic construct, and you cannot invent new ones - certainly not in PHP, and not most (all?) other languages either.
Aside from that, what you are doing is not pushing an item on to the array. For one thing, pushing items implies an indexed array (yours is associative), and for another pushing implies adding a key to the array (the key you want to update already exists).
You can write a function to do it, something like this:
function array_update(&$array, $newData, $where = array(), $strict = FALSE) {
// Check input vars are arrays
if (!is_array($array) || !is_array($newData) || !is_array($where)) return FALSE;
$updated = 0;
foreach ($array as &$item) { // Loop main array
foreach ($where as $key => $val) { // Loop condition array and compare with current item
if (!isset($item[$key]) || (!$strict && $item[$key] != $val) || ($strict && $item[$key] !== $val)) {
continue 2; // if item is not a match, skip to the next one
}
}
// If we get this far, item should be updated
$item = array_merge($item, $newData);
$updated++;
}
return $updated;
}
// Usage
$newData = array(
'group' => '???'
);
$where = array(
'name' => 'Bobby'
);
array_update($list, $newData, $where);
// Input $array and $newData array are required, $where array can be omitted to
// update all items in $array. Supply TRUE to the forth argument to force strict
// typed comparisons when looking for item(s) to update. Multiple keys can be
// supplied in $where to match more than one condition.
// Returns the number of items in the input array that were modified, or FALSE on error.

php arrays: search for matching values in a table and replace with array keys

Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}

Categories