Search for specific value in array with keys - php

I have an array that is filled with values dynamically and I have to check if a value exists.
I tried the follwing but it's not working:
while (.....) {
$fileData[] = array( "sku" => $sku, "qty" => $qty);
}
$product_sku = $product->getSku();
if (in_array(array("sku",$product_sku), $fileData)){
echo "OK <BR/>";
}
else{
echo "NOT FOUND <BR/>";
}
The whole thing with keys confuses me. Should I change the table structure or just the in_array() statement? Can you help me find a solution?

You can see if a key exists in an array with:
array_key_exists('sku', $fileData);
also, you can just check it directly:
if (isset($fileData['sku'])
It looks like you might be trying to recursively check for a key though? I think we'd need to see what getSku() returns. $fileData[] appends a value to an existing array so if $fileData was an empty array you'd have
fileData[0] = array("sku" => $sku, "qty" => $qty);
not
fileData = array("sku" => $sku, "qty" => $qty);
Try this on for size (with some fake data for demo purposes):
$fileData = array(
array("sku" => "sku1", "qty" => 1),
array("sku" => "sku2", "qty" => 2),
);
$sku = "sku2"; // here's the sku we want to find
$skuExists = false;
// loop through file datas
foreach ($fileData as $data)
{
// data is set to each array in fileData
// check if sku exists in that array
if (in_array($sku, $data))
{
// if it does, exit the loop and flag
$skuExists = true;
break;
}
}
if ($skuExists)
{
// do something
}

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);
});

PHP Remove Multidimensional Array Value

I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);

Easier to put $_POST With Array

I did try many times to make values easier to put. It's my meaning to put values with array, because I don't need to type more values then, he can put it automatically.. For example, I write:
<?php
$Value1 = array (
'Somevalue1' => 'SomeValue2',
'SomeValue1' => 'SomeValue2',
'SomeValue1' => 'SomeValue2',
);
// This is method what i want to put in, but i dont think that its right
$Value1[0] = strip_tags($_POST['.Value1[0].']);
// Its the meaning that he put so out:
$SomeValue1 = strip_tags($_POST['SomeValue2']);
$SomeValue1 = strip_tags($_POST['SomeValue2']);
$SomeValue1 = strip_tags($_POST['SomeValue2']);
?>
I don't have to much experience with array, I am just learning...
I guess it is this what you want to do:
// create an array with key = field-name in form
$val = array(
'name' => null,
'lastname' => null,
'date_of_birth' => null,
'favorite_color' => null);
if (isset($_POST['submit'])) { // form has been sent
// retrieve values from $_POST and store it in $val
foreach ($val as $key => $value)
$val[$key] = $_POST[$key];
// show the result
echo "<pre>";
var_dump($val);
echo "</pre>";
} // if isset
see live demo: http://codepad.viper-7.com/j03DtO

in_array function not working right

I am using a multidimensional array to hold the variables for a given page. I am trying to get a string from the url and match it with an array within my template array to pull the correct variables to display on the page.
Here is my array:
$template = array(
"index" => array(
"title" => "Dashboard",
"model" => "model/dash.php"
),
"input" => array(
"title" => "Dashboard",
"model" => "model/input.php"
),
"jobboard" => array(
"title" => "Job Board",
"model" => "model/job_board.php"
),
"jobcreate" => array(
"title" => "Job Creator",
"model" => "model/job_create.php"
)
);
And here is what I am using to try and verify the pages:
if(isset($_GET['page'])){ $page = $_GET['page']; }
if(in_array($page, $template)){
$title = $template[$page]['title'];
$model = $template[$page]['model'];
echo "yes";
}else{
$title = $template['index']['title'];
$model = $template['index']['model'];
echo "no";
}
The echo "yes/no"; is what I am using to debug if it is working or not but no matter what I have done it just keeps on outputting no.
Take a look at the documentation of php's in_array()
in_array — Checks if a value exists in an array
It looks like your intention is to check against the index of the array, rather than the value. The values in the array are arrays.
Try using array_key_exists() instead.
if (array_key_exists($page, $template)) {
$title = $template[$page]['title'];
$model = $template[$page]['model'];
echo "yes";
}
else {
$title = $template['index']['title'];
$model = $template['index']['model'];
echo "no";
}
in_array() looks at values. It is probably keys you're after.
You can check that with array_key_exists().

if one array element similar to request variable, then how to fetch another elements of array

I am asking Similar question compare request values to array - it doesn't work to me, my scenario is totally different
$mkt = array(
array(
'title' => "Photos",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'test'
),
array(
'title' => "code",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'main'
),
array(
'title' => "code",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'main'
));
I am having logic issue in this problem, problem is i am getting value via $_REQUEST variable and then i compare this request value to array pkg element. If comparison is true then i want to get another elements except to matched one. In this as suggested, i am using unset to remove the key of element which is matched and all array point to new variable, it working but not for first element of array, it shows null when i compare request variable to first element of array:
$mkt = array();
$newArray = $mkt;
foreach ($newArray as $key => $value ) {
if (in_array($pn, $mkt, true)) {
unset($newArray[$key]);
}
}
$rand_ad = array_rand( $newArray, 1 );
echo json_encode( $newArray[$rand_ad] );
Please have a look on this issue very grateful to me.
Loop in each value, if $pn is equal with that loop's pkg then unset than unset that element:
$pn = 'main';
$newArray = $mkt;
foreach ($newArray as $key => $val) {
if ($pn == $val['pkg']) {
unset($newArray[$key]);
}
}
echo json_encode($newArray);
// [{"title":"Photos","iconlink":"http:\/\/example.com\/xyz.png","pkg":"test"}]

Categories