Searching in multi dimensional array using array_search - php

I have an array with the following setup:
array(
array(
'product_id' => 733
),
array(
'product_name' => Example
)
)
I want to check that 733 exists in my array which I need to use array_search (going by googling) as in_array doesn't work on m-d arrays.
My code is:
$key = array_search( '733', array_column( $items, 'product_id' ) );
If I var_dump the $items array I can see the product_id
I want to check the specific ID exists in the array and then perform other code.

So basically you want to check that given product-id exist in your multidimensional array or not?
You can do it like below:-
<?php
$items = array(
array(
'product_id' => 733
),
array(
'product_name' => Example
)
);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if (!empty($val['product_id']) && $val['product_id'] == $id) {
return "true"; // or return key according to your wish
}
}
return "false";
}
echo $found = searchForId(733, $items);
Output:- https://eval.in/805075
Reference taken:- https://stackoverflow.com/a/6661561/4248328

Related

How to match 2 arrays, and loop through to display an array value?

I'm trying to match two arrays, if matched then loop through array value to display them on the page.
This is how I am doing it.
$productIDs = array(
'0' => array(
'product_id' => '565355',
'product_name' => 'stackPDF',
'product_file' => 'http://www.example.com/stack.pdf',
),
'1' => array(
'product_id' => '563423',
'product_name' => 'lostPDF',
'product_file' => 'http://www.example.com/lost.pdf',
),
'3' => array(
'product_id' => '4442',
'product_name' => 'No product',
'product_file' => '',
)
);
function getProducts($productIDs){
$getIDs = explode(',', $_GET['product_id']);
$intersection = array();
foreach($productIDs as $items)
{
$intersection[] = array_intersect($items, $getIDs);
}
if(!empty($intersection)){
return $intersection;
} else {
echo "There are no products available!";
}
}
$getProducts = getProducts($productIDs);
function getDownloads($getProducts){
foreach($getProducts as $item){
print_r($item);
}
}
$getDownloads = getDownloads($getProducts);
In the getProducts() function, I'm checking to see if the product_id in the header match any of the product_id in $productIDs, to only show the available links for those that are in the header.
$getProducts variable has the available product_id that's already matched in an array, and in the $getDownloads I was trying to "If id's are available, loop through and display the product_file parameter value from the multidimensional array" but I can't seem to loop through it, rather I can't figure out how to match it/return the values.
array_filter($array, function($v) use($id){ return $v['product_id'] == $id;})
The easiest way I can think of is:
$item_exists = array_filter($productIDs, function($item) use ($check) {
return md5(json_encode($item)) == md5(json_encode($check));
});
json_encode will serialize the array to string and md5 will create a compare key, if they are equal, it will be inserted in the $item_exists array.
Edit: I was thinking of comparing product objects, but I guess you need the ID's only, you can use something like this:
$existing_values = array_filter($productIDs, function($p)use($getIDs){
return in_array($p["product_id"], $getIDs);
});

Loop over one array as if it was a multidimensional array

I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);

PHP - array key within array value

I have a PHP array like this:
$arr = array(
'id' => 'app.settings.value.id',
'title' => 'app.settings.value.title',
'user' => 'app.settings.value.user'
);
I want to remove '.id', '.title' and '.user' in the array values. I want to insert the key of this array at the end of the value. I know, that I can get an array key by passing an array and a value to 'array_search', but I want the key within this one array definition - at the end of it's value. Is this possible?
I don't like this, but I guess it's simple and works:
$arr = array(
'id' => 'app.settings.value',
'title' => 'app.settings.value',
'user' => 'app.settings.value'
);
$result = array();
foreach ($arr AS $key => $value) {
$result[$key] = $value . '.' . $key;
}
You're storing app.settings.value which is the same for all array items, so personally I'd prefer:
$arr = array(
'id',
'title',
'user'
);
function prepend_key($key)
{
return 'app.settings.value.' . $key;
}
$result = array_map('prepend_key', $arr);
With $result containing:
array(
'app.settings.value.id',
'app.settings.value.title',
'app.settings.value.user'
);
At the end of the day, either works :)

How to search multiple keys from predefined array?

i have predefined array of categories like this in key => value pair
$all_categories = array (
1 => 'friends',
2 => 'family',
3 => 'personal',
4 => 'public'
);
and i have new small array like this which are only values.
$searched_categories = array('family','public');
Now how can i get the keys from $all_categories array having values as $searched_categories ?
i want output like this
$output_array = array(2,4);
i can get single key using array_search but is there a prebuilt function for this ? or i have to create a loop to array_search all the values i have ?
is this proper way of achieving this ?
$output_array = array ();
foreach ($searched_categories as $value){
$key = array_search($value, $all_categories );
$output_array = $key;
}
$all_categories = array (1 => 'friends', 2 => 'family', 3 => 'personal', 4 => 'public');
$searched_categories = array('family','public');
$output_array = array_keys(
array_intersect(
$all_categories,
$searched_categories
)
);
var_dump($output_array);
You could use a foreach loop and in_array.
foreach($all_categories as $key => $category){ //loop through your categories array
if(in_array($category, $searched_categories)){ //check if category is in searched_catgories
$output_array[] = $key; //if category is there, then save the key to your new array
}
}
print_r($output_array); will give you Array ( [0] => 2 [1] => 4 )
array_search is doing the job, but you erase your array all the time and add $key regardless of the fact it could be equal to false from array_search :
foreach ($searched_categories as $value){
$key = array_search($value, $all_categories );
if ($key !== false)
$output_array[] = $key;
}

Find Value in Array

The following array is output from my db.
$this->db->select('code')->from('table');
$array = $this->db->get()->result_array();
//Output:
Array ( [0] => Array ( [code] => ASDF123 ) [1] => Array ( [code] => ASDF124 ) )
How can I find if a variable is contained in this array?
ie.
if(this_is_in_array($value, $array) == TRUE)...
What's the simplest way to to that with PHP?
I sincerely apologize for not wording this correctly the first time.
In case you wish to find the KEY of an array you would refer to the array_key_exists() method.
An example of this would be:
$array = array(
'key1' => 'value1',
'key2' => 'value2'
);
if ( array_key_exists( 'key2', $array ) )
return TRUE;
If you would however prefer to find the VALUE of an array, you would refer to the in_array() method. An example of this would be:
$array = array(
'key1' => 'value1',
'key2' => 'value2'
);
if ( in_array( 'value1', $array ) )
return TRUE;
Kevin:
foreach( $array as $key => $values )
{
if ( $values['code'] == 'ASD1234' )
{
// do something
}
}
make your array this:
$your_array = array('key1'=>'value1', 'key2'=>'value2');
then use this to see if the key exists in the array.
if (array_key_exists('key2', $your_array)) {
Unsure about what exactly you mean in your question, however, to answer your question title, you can use the array_key_exists() function to check if a given key or index exists within an array.
put your validation into the function
$input = 'ASDF123';
function check_input($input) {
$array = array(
0 => array('code' => 'ASDF123'),
1 => array('code' => 'ASDF124')
);
foreach ($array as $codes) {
if (in_array($input, $codes)) {
return true;
}
}
return false;
}
$needle = 'ASDF123';
$ary = Array(
Array('code' => 'ASDF123'),
Array('code' => 'ASDF124')
);
$_ = "return (\$a['code']='".addslashes($needle)."');";
if (count(array_filter($ary[0],create_function('$a',$_))) > 0)
//true
I THINK (only because you use code twice, so I assume that's not the search field--or it's a semantics issue). If it is semantics, as everyone else has already suggested, try array_key_exists.

Categories