I have array like below.
(
[TestData1] => Array
(
[0] => Array
(
[SKU] => A01
[SKUType] => Test
[State] => Yes
)
[1] => Array
(
[SKU] => A02
[SKUType] => Test
[State] => Yes
)
[2] => Array
(
[SKU] => A01
[SKUType] => Test
[State] => Yes
)
[3] => Array
(
[SKU] => A03
[SKUType] => Test
[State] => Yes
)
)
[TestData2] => Array
(
)
[TestData3] => Array
(
)
)
I need to check if the given SKU is exist or not in the TestData1 array.
If exist need to check the State value that should be Yes.
Example given sku is
$skutotest = 'A01';
How to find if the value present in the above array using PHP.
Right now i tried like below.
$Details = result_array; // here reading array data from api
$parent_sku = A01;
$Results = $Details['$TestData1'];
foreach($Results as $res){
$sku= $res['SKU'];
$state = $res['State'];
if($sku== $parent_sku && $state == "Yes"){
return true;
break;
}else{
return false;
}
}
Once i found the match, need to stop executing and return true, is the above code correct?
Can anyone help me with this. Thanks
Check this one liner,
$exists = false;
$key = "TestData1";
$skutotest = "A01";
if (array_key_exists($key, $arr)) { // for check if key exists
return ($arr[$key][array_search($skutotest, array_column($arr[$key], 'SKU'))]['State'] == 'Yes');
}
array_search — Searches the array for a given value and returns the first corresponding key if successful
array_column — Return the values from a single column in the input array
Demo.
EDIT
Proper solution for your problem,
$exists = false;
$key = "TestData1";
$val = "A01";
if (array_key_exists($key, $arr)) {
array_walk($arr[$key], function ($item) use ($val, &$exists) {
if ($item['SKU'] == $val && $item['State'] == 'Yes') {
$exists = true;
return;
}
});
}
return ($exists);
Demo
Following function has been used in the solution :
array_combine() - Creates an array by using one array for keys and another for its values
array_column() - Return the values from a single column in the input array
array_key_exists() - Checks if the given key or index exists in the array
$skuToSearch = 'A01';
$parentKey = 'TestData1';
$res = array_combine(
array_column($arr[$parentKey] , 'SKU'),
array_column($arr[$parentKey] , 'State')
);
$found = (array_key_exists($skuToSearch, $res) && $res[$skuToSearch] == 'Yes') ? true : false;
Explanation:
variable $skuToSearch, put the SKU which you want to search.
variable $parentKey hold the key of the parent subarray.
array_column($arr[$parentKey] , 'SKU') will return an array with SKU's
array_column($arr[$parentKey] , 'State') will return an array with States
Variable $found will return true OR false, if the SKU found and have state values Yes
Related
I need the Id if the 'Final' text match on this array. Like this for array one 288617 and for array two 288031.
Array
(
[0] => a:4:{i:0;s:11:"Demo Course";i:1;s:6:"288616";i:2;s:10:"Final Exam";i:3;s:6:"288617";}
)
Array
(
[0] => a:29:{i:0;s:16:"Sage 50 Accounts";i:1;s:6:"287967";i:2;s:6:"278823";i:3;s:6:"278824";i:4;s:6:"278825";i:5;s:6:"278826";i:6;s:6:"278856";i:7;s:6:"278857";i:8;s:6:"278858";i:9;s:6:"278859";i:10;s:6:"278860";i:11;s:6:"278861";i:12;s:6:"278862";i:13;s:6:"279608";i:14;s:6:"279609";i:15;s:6:"279610";i:16;s:6:"279611";i:17;s:6:"278821";i:18;s:6:"279612";i:19;s:6:"279613";i:20;s:6:"279681";i:21;s:6:"279677";i:22;s:6:"279678";i:23;s:6:"279679";i:24;s:6:"279680";i:25;s:9:"Mock Exam";i:26;s:6:"288030";i:27;s:10:"Final Exam";i:28;s:6:"288031";}
)
I have tried with this code, but can't work.
$search_text = 'Final';
array_filter($array, function($el) use ($search_text) {
return ( strpos($el['text'], $search_text) !== false );
});
First you have to unserialize that text. Then the simplest way is to loop and check for the text and then take the next element:
$array[0] = unserialize($array[0]);
$search_text = 'Final';
foreach($array[0] as $key => $value){
if(strpos($value, $search_text) !== false) {
$result = $array[0][$key+1];
break;
}
}
This assumes that the array is paired the way you have shown:
Array
(
[0] => Demo Course
[1] => 288616
[2] => Final Exam
[3] => 288617
)
With your second array it would only return the first ID 287967 if you search on Sage.
Try end function.
This function return the last element of your array
$array = ['sample1', 'sample2', ... ,'Final';
$search_text = 'Final';
if(end($aray) == $search_text){
// find
}else{
// not found
}
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']);
I have the following array:
Array
(
[0] => Array
(
[CODE] => OK
[company_id] => 170647449000
[taxnumber] => 944703420
[name] => SOME NAME
[title] => S.A
)
[1] => Array
(
[CODE] => OK
[company_id] => 17063649000
[taxnumber] => 999033420
[name] => SOME OTHER NAME
[title] => ANOTHER DIFFERENT TITLE
)
)
If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.
I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:
function myfunction($agents, $field, $value)
{
foreach($agents as $key => $agent)
{
if ( $agent[$field] === $value )
return $key;
}
return false;
}
I always get false, even I am sending the value that exists.
Replace return $key with return $agent and operator === with ==.
=== checks type too, it could be reason why it doesn't work.
if your array is $companies then
function getCompany($search_id, $companies) {
foreach($company in $companies) {
if ($companies['company_id'] == $search_id) {
return $company;
}
}
return false;
}
$companies = [...];
$search = 17063649000;
if ($company = getCompany($search, $companies) ) {
// do something with $company
} else {
// not found
}
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
How do I know if a key in an array is true? If not, then don't use this
[0] => array
(
[id] => 1
[some_key] => something
)
[1] => array
(
[id] => 2
)
[2] => array
(
[id] => 3
[some_key] => something
)
foreach($array as $value){
$id = $value->id;
if($value->some_key === TRUE){
$some_key = $value->some_key; //some may have this key, some may not
}
}
Not sure what is the proper statement to check if this array has that some_key. If I don't have a check, it will output an error message.
Thanks in advance.
Try
isset($array[$some_key])
It will return true if the array $array has an index $some_key, which can be a string or an integer.
Others have mentioned isset(), which mostly works. It will fail if the value under the key is null, however:
$test = array('sampleKey' => null);
isset($test['sampleKey']); // returns false
If this case is important for you to test, there's an explicit array_key_exists() function which handles it correctly:
http://php.net/manual/en/function.array-key-exists.php
You can use the isset() function to see if a variable is set.
foreach($array as $value){
$id = $value->id;
if(isset($value->some_key)){
$some_key = $value->some_key;
}
}
function validate($array)
{
foreach($array as $val) {
if( !array_key_exists('id', $val) ) return false;
if( !array_key_exists('some_key', $val) ) return false;
}
return true;
}