here is my array:
[0] => Array
(
[messages] => Array
(
[0] => Array
(
[message] => This is for sandwich
)
[1] => Array
(
[message] => This message is for burger
)
)
[price] => Array
(
[amount] => 5
[currency] => USD
)
[1] => Array
(
[messages] => Array
(
[0] => Array
(
[message] => This is a message for a delicious hotdog
)
)
[price] => Array
(
[amount] => 3
[currency] => USD
)
)
i want to search in ALL arrays and I want to search for the word "burger". I want to get the price and amount of "burger" which is 5. If I search for the word "hotdog", it will return the price amount 3. How can i do that? thanks
You can use a foreach loop and then use strpos or stripos.
foreach ($array as $row) {
foreach ($row['messages'] as $row2) {
if(strpos($row2['message'], 'burger') !== false) {
$stringFound = true;
} else {
$stringFound = false;
}
}
if($stringFound === true) {
$price = $row['price']['amount'];
} else {
$price = '0';
}
}
echo $price;
If $array be your array. I Think It may Work.
<?php
$check = 'hotdog';
foreach($array as $products){
foreach($products['messages'] as $messages){
if (strpos($messages['message'], $check) !== false) {
echo $check.' Found. Price'. $products['price']['amount'] .'</br>' ;
}
}
}
?>
Here we are using array_column, implode and preg_match.
1. array_column for retrieving specific column of an array
2. implode joins a array with a glue to make it string.
3. preg_match here for matching specific word in the given string.
Try this code snippet here
$toSearch="hotdog";
foreach($array as $key => $value)
{
if(preg_match("/\b$toSearch\b/",implode(",",array_column($value["messages"],"message"))))
{
echo $value["price"]["amount"];
}
}
Because you are searching for the first qualifying price only, it is best practice to use a conditional break to short circuit the loops. There is no reason to do more cycles if you have found a qualifying entry.
Instantiate the $amount variable with a null value before the loop to properly distinguish between a successful search and an unsuccessful one.
str_contain() is the modern function to case-sensitively search for a substring (PHP7.4 and higher). If you need case-insensitivity, you will need to use stripos($message['message'], $needle) !== false. If you need to match whole words, you will need to call preg_match("/\b$needle\b/i", $message['message']). If using regex and the $needle is coming from user input, you will need to apply escaping beforehand with $needle = preg_quote($needle, '/');.
Code: (Demo)
$needle = 'burger';
$amount = null;
foreach ($haystack as ['messages' => $messages, 'price' => $price]) {
foreach ($messages as $message) {
if (str_contains($message['message'], $needle)) {
$amount = $price['amount'];
break;
}
}
}
var_export($amount);
// 5
Related
I get some data from the database, which is saved in "$Data". $Data looks like this:
[Data] => Array
(
[0] => Array
(
[PrinterID] => 3
[PrinterName] => PRT03_EDV
[isDefaultPrinter] => 1
[isMapped] => 0
)
[1] => Array
(
[PrinterID] => 1
[PrinterName] => PRT01_Zentral
[isDefaultPrinter] => 0
[isMapped] => 1
)
[2] => Array
(
[PrinterID] => 2
[PrinterName] => PRT02_BH
[isDefaultPrinter] => 0
[isMapped] => 0
)
I need to verify, that there is no array in $Data, where "isDefaultPrinter == True" and "isMapped == False". Programatically:
if ( $Data["isDefaultPrinter"] == true and $Data["isMapped"] == false ) {
// Remove from Array
}
I did start to code this on my own based on this and my result was a terrible looking nested loop, which did not work :-(
I am a beginner and I wanted to ask, if there is an nice and easy way to do this?
Thank you
Here's a version using array_filter, which is sort of built for this. See http://php.net/manual/en/function.array-filter.php
$valid = array_filter($Data, function($var) {
return !($var['isDefaultPrinter'] && !$var['isMapped']);
});
Use foreach to loop over the data array:
foreach ($Data['Data'] as $entry) {
// Examine every entry
if ($entry['isDefaultPrinter'] && !$entry['isMapped']) {
// $entry does not meet criteria
}
}
You can write a function that verifies that every entry meets your criteria:
function validateData($Data) {
foreach ($Data['Data'] as $entry) {
// Examine every entry
if ($entry['isDefaultPrinter'] && !$entry['isMapped']) {
// $entry does not meet criteria
return false;
}
}
// Everything is OK
return true;
}
var_dump(validateData($Data));
You can use unset to remove the row of the array that doesn't fit your "keep" criteria. You need to know the array key to remove it tidily; this foreach with the $key value as well:
foreach ($var['Data'] as $key => $entry) {
// Examine every entry
if ($entry['isDefaultPrinter'] && !$entry['isMapped']) {
// $entry does not meet criteria
unset($var['Data'][$key]);
}
}
print_r($var); //output remaining values.
Once completed - and if you wish - you can then reindex the [outer] array using array_values():
$var['Data'] = array_values($var['Data']);
Hi i am working on some operations where i need to get value of array from its key.
I have $attr_color variable with the value red.
So if red is in the array then it needs to be return its value.
Below is my array :
Array
(
[0] => Array
(
[label] =>
[value] =>
)
[1] => Array
(
[label] => red
[value] => 32
)
[2] => Array
(
[label] => green
[value] => 33
)
[3] => Array
(
[label] => pink
[value] => 34
)
[4] => Array
(
[label] => black
[value] => 35
)
[5] => Array
(
[label] => white
[value] => 36
)
)
I have tried below code but it returns blank :
$attr_color = "red";
//$response is my array which i have mention above.
if(in_array($attr_color,array_column($response,"label")))
{
$value = $response['value'];
echo "Value".$value;
exit;
}
Help ? where i made mistake ?
Use array_search, and check for false:
$index = array_search($attr_color, array_column($response,"label"));
if ($index !== false) {
echo $response[$index]['value'];
}
In your case it's enough to use a regular foreach loop:
$attr_color = "red";
$value = "";
foreach ($response as $item) {
if ($item['label'] == $attr_color) {
$value = $item['value'];
break; // avoids redundant iterations
}
}
Try this simple solution, hope this will help you out. Here we are using array_column for getting columns and indexing it with keys and values, Where keys are labels and values as value
Try this code snippet (with sample inputs)
$result=array_column($array, 'value',"label");
$result=array_filter($result);
echo $result["red"];
By using array_column with third parameter and array_search as
$attr_color="red";
$arr = array_filter(array_column($response, "label", 'value'));// pass thired parameter to make its key
if (array_search($attr_color, $arr)) {// use array search here
echo array_search($attr_color, $arr);
}
Try below code : using array match function :
$your_value = array_search($attr_color, array_column($response,"label"));
if ($index !== false) {
echo $response[$your_value]['value'];
}
Try:
$attr_color = "red";
//$response is my array which i have mention above.
$index = array_search($attr_color, array_column($response, 'label'));
if($index!==false){
$value = $response[$index]['value'];
echo "Value:".$value;
exit;
}
Here $index will get the index of the array with label red
Use array_search instead of in_array
$attr_color = "red";
if(($index = array_search($attr_color,array_column($response,"label")))!==FALSE)
{
$value = $response[$index]['value'];
echo "Value".$value;
exit;
}
Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best
hey guys i have a array such as
$return = array(
'GPPZ20'=>'5.00',
'GPPZ45'=>'10.00',
'GPPZ75'=>'15.00',
'GPPZH20'=>'5.00',
);
i also have a array thats
[0] => Array
(
[main_company] => Marketing
[code] => GPPZH20XSYDLDJ
[company] => All Companies
)
[1] => Array
(
[main_company] => Some Company
[code] => XHJDOJSHHJYD
[company] => All Companies
)
and so on
what i need to do is grab the code value from the second array and check if any of the first few characters match any of the ones in the return array and if so grab the value from the return array.
I can specify the first 5 characters or 6 because the keys in the return array can be any number but they are always the beginning of the the code.
Any ideas or help is greatly appreciated.
All you need is
foreach ( $data as $v ) {
foreach ( $return as $k => $f ) {
if (strpos($v['code'], $k) === 0) {
printf("%s %s %f \n", $v['main_company'], $v['code'], $f);
}
}
}
Output
Marketing GPPZH20XSYDLDJ 5.000000
Assuming you have already a code value from your second array, cut off the first part of it.
$code = $array[0]['code'];
$str = substr($code, 0, 5);
foreach($return as $key=>$element){
if($key==$str){
echo $element;
}
}
I'm fetching some JSON from flickrs API. My problem is that the exif data is in different order depending on the camera. So I can't hard-code an array number to get, for instance, the camera model below. Does PHP have any built in methods to search through associative array values and return the matching arrays? In my example below I would like to search for the [label] => Model and get [_content] => NIKON D5100.
Please let me know if you want me to elaborate.
print_r($exif['photo']['exif']);
Result:
Array
(
[0] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Make
[label] => Make
[raw] => Array
(
[_content] => NIKON CORPORATION
)
)
[1] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => Model
[label] => Model
[raw] => Array
(
[_content] => NIKON D5100
)
)
[2] => Array
(
[tagspace] => IFD0
[tagspaceid] => 0
[tag] => XResolution
[label] => X-Resolution
[raw] => Array
(
[_content] => 240
)
[clean] => Array
(
[_content] => 240 dpi
)
)
$key = array_search('model', array_column($data, 'label'));
In more recent versions of PHP, specifically PHP 5 >= 5.5.0, the function above will work.
To my knowledge there is no such function. There is array_search, but it doesn't quite do what you want.
I think the easiest way would be to write a loop yourself.
function search_exif($exif, $field)
{
foreach ($exif as $data)
{
if ($data['label'] == $field)
return $data['raw']['_content'];
}
}
$camera = search_exif($exif['photo']['exif'], 'model');
$key = array_search('Model', array_map(function($data) {return $data['label'];}, $exif))
The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function. In this case we are returning the label.
The array_search() function search an array for a value and returns the key. (in this case we are searching the returned array from array_map for the label value 'Model')
This would be fairly trivial to implement:
$model = '';
foreach ($exif['photo']['exif'] as $data) {
if ($data['label'] == 'Model') {
$model = $data['raw']['_content'];
break;
}
}
foreach($exif['photo']['exif'] as $row) {
foreach ($row as $k => $v) {
if ($k == "label" AND $v == "Model")
$needle[] = $row["raw"];
}
}
print_r($needle);
The following function, searches in an associative array both for string values and values inside other arrays. For example , given the following array
$array= [ "one" => ["a","b"],
"two" => "c" ];
the following function can find both a,b and c as well
function search_assoc($value, $array){
$result = false;
foreach ( $array as $el){
if (!is_array($el)){
$result = $result||($el==$value);
}
else if (in_array($value,$el))
$result= $result||true;
else $result= $result||false;
}
return $result;
}
$data = [
["name"=>"mostafa","email"=>"mostafa#gmail.com"],
["name"=>"ali","email"=>"ali#gmail.com"],
["name"=>"nader","email"=>"nader#gmail.com"]];
chekFromItem($data,"ali");
function chekFromItem($items,$keyToSearch)
{
$check = false;
foreach($items as $item)
{
foreach($item as $key)
{
if($key == $keyToSearch)
{
$check = true;
}
}
if($check == true)
{break;}
}
return $check;}
As far as I know , PHP does not have in built-in search function for multidimensional array. It has only for indexed and associative array. Therefore you have to write your own search function!!