PHP: How to get values from array using clause? - php

Hi all I have an array
$data = array("https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
"https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
"https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
"https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg");
How can I get specific data from the array using a clause?
eg. I want to pull a data from the array with 121.jpg.
Thanks!

You can loop the array and check the value:
while (list($key, $value) = each ($data)) {
if(strpos($value, '121.jpg') !== false)
{
var_dump($value);
}
}

May be you mean Closure ? What if there are multiple images with the same name ?
function get_image_url($name, array $images) {
$image_url = array_filter($images, function($value) use ($name) {
return (preg_replace('/^(.*\/)/', '', $value) == $name);
});
if (0 == sizeof($image_url)) {
return false;
} elseif (1 == sizeof($image_url)) {
return reset($image_url);
}
return $image_url;
}
Example:
$images = array(
"https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
"https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
"https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
"https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg",
"121.jpg"
);
var_dump(get_image_url('111.jpg', $images));
// string(103) "https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg"
var_dump(get_image_url('121.jpg', $images));
// array(2) {
// [3] =>
// string(103) "https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg"
// [4] =>
// string(7) "121.jpg"
// }
var_dump(get_image_url('invalid.jpg', $images));
// bool(false)

Related

Search inside multidimensional array and return other key value

I have the following
Multidimensional array.
What I'm trying to do is to search for an IDITEM value and if it's found, return the value of the "PRECO" key.
I'm using the following function to check if the value exists and it works fine, but I can't find a way to get the "PRECO" value of the found IDITEM.
Function:
function search_array($needle, $haystack) {
if(in_array($needle, $haystack)) {
return true;
}
foreach($haystack as $element) {
if(is_array($element) && search_array($needle, $element))
return true;
}
return false;
}
Anyone can help me with that?
You can change the first if statement to return it instead of returning a boolean :
function search_array($needle, $haystack) {
if(in_array($needle, $haystack) && array_key_exists('PRECO', $haystack)) {
return $haystack['PRECO'];
}
foreach($haystack as $element) {
if(is_array($element))
{
$result = search_array($needle, $element);
if($result !== false)
return $result;
}
}
return false;
}
The easiest idea I can remember is converting that boolean search_array into a path creator, where it will return the path for the item, or false if it isn't found.
function get_array_path_to_needle($needle, array $haystack)
{
if(in_array($needle, $haystack))
{
return true;
}
foreach($haystack as $key => $element)
{
if(is_array($element) && ($path = get_array_path_to_needle($needle, $element)) !== false)
{
return $path === true ? $key : $key . '.' . $path;
}
}
return false;
}
Then, since you already have the path, then rerun the array to fetch the item
function get_array_value_from_path(array $path, array $haystack)
{
$current = $haystack;
foreach($path as $key)
{
if(is_array($current) && array_key_exists($key, $current))
{
$current = $current[$key];
}
else
{
return false;
}
}
return $current;
}
This wont get you the PRECO, but it will return the item (array) where id found the value you searched for.
So a simple usage would be:
$path = get_array_path_to_needle('000000000000001650', $data);
$item = get_array_value_from_path(explode('.', $path), $data);
// here you have full array for that item found
print_r($item);
// here you have your price
print_r($item['PRECO']);
Use a static variable to remember the status between multiple function calls, and also to store the desired PRECO value. It makes the function remember the value of the given variable ($needle_value in this example) between multiple calls.
So your search_array() function should be like this:
function search_array($needle, $haystack){
static $needle_value = null;
if($needle_value != null){
return $needle_value;
}
foreach($haystack as $key => $value){
if(is_array($value)){
search_array($needle, $value);
}else if($needle == $value){
$needle_value = $haystack['PRECO'];
break;
}
}
return $needle_value;
}
This function will finally return $needle_value, which is your desired PRECO value from the haystack.
The simplest way is to use a foreach loop twice. Check for the key and store the result into an array for later use.
Based on your array, the below
$search = '000000000000001650';
foreach($array as $element){
foreach ($element['ITEM'] as $item){
if (isset($item['IDITEM']) and $item['IDITEM'] == $search){
$results[] = $item['PRECO'];
}
}
}
print_r($results);
Will output
Array
(
[0] => 375
)
Here is the simple example with array:
// your array with two indexes
$yourArr = array(
0=>array(
'IDDEPARTAMENTO'=>'0000000001',
'DESCRDEPT'=>'Área',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001367',
'DESCRITEM'=>'PISTA TESTE DRIV',
'PRECO'=>'1338.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001925',
'DESCRITEM'=>'PISTA TESTE DRIV2',
'PRECO'=>'916'),
)
),
1=>array(
'IDDEPARTAMENTO'=>'0000000010',
'DESCRDEPT'=>'Merch',
'ITEM'=>
array(
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000002036',
'DESCRITEM'=>'PISTA TESTE DRIV23',
'PRECO'=>'200.78'),
array(
'SETID'=>'RX',
'IDITEM'=>'000000000000001608',
'DESCRITEM'=>'PISTA CRACHÁ DRIV4',
'PRECO'=>'44341'),
)
));
// solution
$newArr = array();
foreach ($yourArr as $value) {
foreach ($value as $key => $innerVal) {
if($key == 'ITEM'){
foreach ($innerVal as $key_inner => $keyinner) {
if(!empty($keyinner['IDITEM'])){
$newArr[$keyinner['IDITEM']] = $keyinner['PRECO'];
}
}
}
}
}
echo "<pre>";
print_r($newArr);
Result values with IDITEM:
Array
(
[000000000000001367] => 1338.78
[000000000000001925] => 916
[000000000000002036] => 200.78
[000000000000001608] => 44341
)

array_key_exists in php with NULL Values giving no output

I have the following query:
//product density
$stmt_density = $conn->prepare("SELECT density FROM product_density
WHERE product_id = :productid ");
$stmt_density->execute(array(':productid' => "$pid"));
$density = $stmt_density->fetchAll();
If density is not present the value will be "NULL".
var_dump($density);
gives following output:
array(1) { [0]=> array(2) { ["density"]=> NULL [0]=> NULL } }
I need to check whether the array is having values or not and to provide select options, if array not empty.
Depending on whether you expect to get back multiple results from your query could change the answer, especially if you get back say 1 result with a NULL and one without. But you could do...
function validResult($density) {
foreach($density as $item) {
if($item["density"] == NULL) return false;
}
return true;
}
if(validResult($density))
echo "We have values";
else
echo "Array contains null";
The function will return false if any result has null, regardless of how many are not null
Try something like this
function check($array, $key)
{
if(array_key_exists($key, $array)) {
if (is_null($array[$key])) {
echo $key . ' is null';
} else {
echo $key . ' is set';
}
}
}
I think you are trying to check for null values in an array try
function array_key_exists_r($needle, $haystack)
{
foreach ($haystack as $v) {
foreach ($v as $k=>$v1) {
if(empty($v1) || $v1 ==$needle)
$result[$k] = $v1;
}
if ($result) return $result;
}
}
$r = array_key_exists_r('NULL', $density);
print_r($r); //Array ( [density] => [0] => )
Function will give you all empty or NULL keys as an array

PHP - How i can find a partial word in array?

I have a word:
$word = "samsung";
I have array:
$myarray = Array(
[0] => "Samsung=tv"
[1] => "Apple=mobile"
[2] => "Nokia=mobile"
[3] => "LG=tv"
I need now something like this to find a partial match:
if($word in $myarray){ echo "YES"; } // samsung found in Samsung=tv
Thank you for help.
You want in_array http://us3.php.net/manual/en/function.in-array.php.
if(in_array($word,$myarray){ echo 'yes'; }
Are you looking for something like this?
<?php
$myarray = array("Samsung=tv", "Apple=mobile", "Nokia=mobile", "LG=tv");
function findSimilarWordInArray($word, $array) {
if (empty($array) && !is_array($array) return false;
foreach ($array as $key=>$value) {
if (strpos( strtolower($value), strtolower($word)) !== false) {
return true;
} // if
} // foreach
}
// use case
if ( findSimilarWordInArray('samsung',$myarray) ) {
echo "I've found it!";
}
?>
It allows you to look for a similar word in array values.
If you are looking for partial matches, you can use strpos() with a foreach loop to iterate through the array.
foreach ($myarray as $key => $value) {
if (strpos($value, $word) !== FALSE) {
echo "Yes";
}
}
There is no built in function to do a partial match, but you can easily create your own:
function in_array_partial($needle, $haystack){
$result = false;
$needle = strtolower($needle);
foreach($haystack as $elem){
if(strpos(strtolower($elem), $needle) !== false){
$result = true;
break;
}
}
return $result;
}
Usage:
if(in_array_partial('samsung', $myarray)){
echo 'yes';
}
You can try something like this:
function my_in_array($word, $array){
forach($array as $value){
if(strpos($word, $value) !== false){
return true;
}
}
return false;
}

check if one of multiple values exists in array

For array with single values like
array(2) {
["blue"]=>
int(0)
["red"]=>
int(1)
}
I use this code
<?php
if (array_key_exists('blue',$array))
{
echo "jo";
}
?>
But what code do I need to use for arrays like this
array(2) {
["yellow blue"]=>
int(0)
["red white"]=>
int(1)
}
to check if blue exists?
My take:
if(preg_grep('/blue/', array_keys($array))) { echo 'found'; }
Or if you want to get them:
$matches = preg_grep('/blue/', array_keys($array));
print_r($matches);
$partialKey = 'blue';
$byPartialKey = function ($key) use ($partialKey) {
$parts = explode(' ', $key);
return in_array($partialKey, $parts);
};
$result = array_filter (array_keys($input), $byPartialKey);
$result now contains all keys, that somehow contains $partialKey.
you can do using regular expression
search='blue';
foreach ($array as $key => $value) {
if (preg_match('~'.$search.'~i',$key)) {
echo "jo";
}
}
The \b in the pattern indicates a word boundary, so only the distinct
word "blue" is matched, and not a word partial like "bluegreen"
search='blue';
foreach ($array as $key => $value) {
if (preg_match('/\b'.$search.'\b/i',$key)) {
echo "jo";
}
}
Reference
I would do it like this:
function subkey_exists($string, $array) {
foreach($array as $key => $value) {
$sub_keys = explode(" ", $key);
if(in_array($string,$sub_keys)) {
return true;
}
}
return false;
}
[edit]
updated to your requirements
Yet another array_filter solution :
<?php
function find_keys_like($key, $array) {
return array_filter(array_keys($array), function($k) use (&$key) {
return strpos($k, $key) > -1;
});
}
function array_has_key_like($key, $array) {
return count(find_keys_like($key, $array)) > 0;
}
//test
$a = array('blue' => 1, 'yellow blue' => 2, 'green' => 3);
print_r(find_keys_like('blue', $a));
echo 'blue exists ? ' . (array_has_key_like('blue', $a) ? 'yes' : 'no') . PHP_EOL;
/** result :
Array
(
[0] => blue
[1] => yellow blue
)
blue exists ? yes
*/

best way to check a empty array?

How can I check an array recursively for empty content like this example:
Array
(
[product_data] => Array
(
[0] => Array
(
[title] =>
[description] =>
[price] =>
)
)
[product_data] => Array
(
[1] => Array
(
[title] =>
[description] =>
[price] =>
)
)
)
The array is not empty but there is no content. How can I check this with a simple function?
Thank!!
function is_array_empty($InputVariable)
{
$Result = true;
if (is_array($InputVariable) && count($InputVariable) > 0)
{
foreach ($InputVariable as $Value)
{
$Result = $Result && is_array_empty($Value);
}
}
else
{
$Result = empty($InputVariable);
}
return $Result;
}
If your array is only one level deep you can also do:
if (strlen(implode('', $array)) == 0)
Works in most cases :)
Solution with array_walk_recursive:
function empty_recursive($value)
{
if (is_array($value)) {
$empty = TRUE;
array_walk_recursive($value, function($item) use (&$empty) {
$empty = $empty && empty($item);
});
} else {
$empty = empty($value);
}
return $empty;
}
Assuming the array will always contain the same type of data:
function TestNotEmpty($arr) {
foreach($arr as $item)
if(isset($item->title) || isset($item->descrtiption || isset($item->price))
return true;
return false;
}
Short circuiting included.
function hasValues($input, $deepCheck = true) {
foreach($input as $value) {
if(is_array($value) && $deepCheck) {
if($this->hasValues($value, $deepCheck))
return true;
}
elseif(!empty($value) && !is_array($value))
return true;
}
return false;
}
Here's my version. Once it finds a non-empty string in an array, it stops. Plus it properly checks on empty strings, so that a 0 (zero) is not considered an empty string (which would be if you used empty() function). By the way even using this function just for strings has proven invaluable over the years.
function isEmpty($stringOrArray) {
if(is_array($stringOrArray)) {
foreach($stringOrArray as $value) {
if(!isEmpty($value)) {
return false;
}
}
return true;
}
return !strlen($stringOrArray); // this properly checks on empty string ('')
}
If anyone stumbles on this question and needs to check if the entire array is NULL, meaning that each pair in the array is equal to null, this is a handy function. You could very easily modify it to return true if any variable returns NULL as well. I needed this for a certain web form where it updated users data and it was possible for it to come through completely blank, therefor not needing to do any SQL.
$test_ary = array("1"=>NULL, "2"=>NULL, "3"=>NULL);
function array_empty($ary, $full_null=false){
$null_count = 0;
$ary_count = count($ary);
foreach($ary as $value){
if($value == NULL){
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return true;
}else{
return false;
}
}else{
if($null_count > 0){
return true;
}else{
return false;
}
}
}
$test = array_empty($test_ary, $full_null=true);
echo $test;
$arr=array_unique(array_values($args));
if(empty($arr[0]) && count($arr)==1){
echo "empty array";
}
Returns TRUE if passed a variable other than an array, or if any of the nested arrays contains a value (including falsy values!). Returns FALSE otherwise.
Short circuits.
function has_values($var) {
if (is_array($var)) {
if (empty($var)) return FALSE;
foreach ($var as $val) {
if(has_values($val)) return TRUE;
}
return FALSE;
}
return TRUE;
}
Here's a good utility function that will return true (1) if the array is empty, or false (0) if not:
function is_array_empty( $mixed ) {
if ( is_array($mixed) ) {
foreach ($mixed as $value) {
if ( ! is_array_empty($value) ) {
return false;
}
}
} elseif ( ! empty($mixed) ) {
return false;
}
return true;
}
For example, given a multidimensional array:
$products = array(
'product_data' => array(
0 => array(
'title' => '',
'description' => null,
'price' => '',
),
),
);
You'll get a true value returned from is_array_empty(), since there are no values set:
var_dump( is_array_empty($products) );
View this code interactively at: http://codepad.org/l2C0Efab
I needed a function to filter an array recursively for non empty values.
Here is my recursive function:
function filterArray(array $array, bool $keepNonArrayValues = false): array {
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = $this->filterArray($value, $keepNonArrayValues);
}
// keep non empty values anyway
// otherwise only if it is not an array and flag $keepNonArrayValues is TRUE
if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) {
$result[$key] = $value;
}
}
return array_slice($result, 0)
}
With parameter $keepNonArrayValues you can decide if values such 0 (number zero), '' (empty string) or false (bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = true only empty arrays will be removed from target array.
array_slice($result, 0) has the effect that numeric indices will be rearranged (0..length-1).
Additionally, after filtering the array by this function it can be tested with empty($filterredArray).

Categories