Get value of specific $_POST array - php

name="qty<?php echo $key?>"
foreach ($_POST as $items => $value)
{
// check qty >1???
echo $key, ' => ', $value, '<br />';
}
How do I show only items which their values of [qty1]=>value,[qty2]=>value... >0 ?

Just use combination of array_filter and print_r.
$_POST = [
'notme' => 12,
'qty1' => 1,
'qty2' => 20,
'qty3' => -1,
'qty4' => 0,
'qty5' => 30
];
print_r(
array_filter($_POST, function ($value, $key) {
// check key starts with 'qty' and its value is greater than one
return strpos($key, 'qty') === 0 && $value > 1;
}, ARRAY_FILTER_USE_BOTH)
);
// Array ( [qty2] => 20 [qty5] => 30 )

Why don't you add a check in your loop and then get a filtered output like this:
if your POST request is not a multidimensional array then use this:
$output = array_filter($_POST, function ($value, $key) {
// check your keys start with 'qty' and its value is greater than one
return strpos($key, 'qty') === 0 && $value > 1;
}, ARRAY_FILTER_USE_BOTH);
// display final output
print_r($output);
If your POST request is a multidimensional array then use this:
$output = array(); // declare a blank array to store filtered output
foreach($_POST as $row)
{
if (is_array($row))
{
// this code is because qty is dynamic and we need to check it for all.
foreach($row as $key => $value)
{
if ("qty" == substr($key, 0, 3) && $value > 0)
{
$output[] = $row;
}
}
}
}
// display final array.
print_r($output);
Hope that will help!

Related

check exist all value every single key in array?

i have an $arrays array like this :
Array
(
[0] => Array
(
[0] => VUM
[1] => UA0885
)
[1] => Array
(
[0] => VUA
[1] => UA0885
)
)
i want to check if input value exist (VUA & UA0885), than not add it to this array.
Ex:
(VUA & UA0885) => not add
(VUB & UA0885) => add
(VUA & UA0886) => add
here is my code:
foreach($arrays as $array){
if($array[0] != $_REQUEST['tourcode'] || $array[1] != $_REQUEST['promocode']){
$arrays[] = array($_REQUEST['tourcode'],$_REQUEST['promocode']);
}
}
Tried use in_array too but it still add a duplicate to $arrays
You can iterate the array, check if the same values are found, and if not push the new values:
$tour = $_REQUEST['tourcode'];
$promo = $_REQUEST['promocode'];
$new = true; //default to true
foreach($arrays as $el){
if($el[0].'-'.$el[1] == $tour. '-' .$promo]){
$new=false;
break; //no need to continue
}
}
if($new) $arrays[]=[$tour,$promo];
foreach($arrays as $key => $array) {
if($array[0] == $_REQUEST['tourcode'] && $array[1] == $_REQUEST['promocode']) {
unset($arrays[$key]);
}
}
To check if there is an entry with tourcode AND promocode already in the array you can use something close to what you had:
function codeInArray($array, $tourcode, $promocode) {
foreach ($array as $entry) {
// check if we have an entry that has the same tour and promo code
if ($entry[0] == $tourcode && $entry[1] == $promocode) {
return true;
}
}
return false;
}
Then you can use it like this:
// run the function and see if its not in the array already
if (!codeInArray($arrays, $_GET['tourcode'], $_GET['promocode'])) {
// add the new entry to `$arrays`
$arrays[] = [
$_GET['tourcode'],
$_GET['promocode'],
];
}
As I understood changing your statement for !in_array might be the solution:
if (!in_array(array($_REQUEST['tourcode'],$_REQUEST['promocode']),$array))
<?php
$array = array(
0=>array(
0=>'VUM',
1=>'UA0885'
),
1=>array(
0=>'VUA',
1=>'UA0885'
)
);
$tour_code = trim($_REQUEST['tourcode']);
$promo_code = trim($_REQUEST['promocode']);
$filterarray = array();
$counter = 0;
foreach($array as $subarray){
foreach($subarray as $key => $value){
if(!in_array($tour_code , $subarray) || !in_array($promo_code , $subarray)){
$filterarray[$counter][] = $value;
}
}
$counter++;
}
print_r($filterarray);
?>

PHP- how to sum array elements with duplicate element value [duplicate]

This question already has answers here:
Group 2d array rows by one column and sum another column [duplicate]
(3 answers)
Closed 4 months ago.
I have a multi array that has some duplicated values that are same by name ( name is an element )
i want to sum quantity of each array that has same name , and then unset the second array
Example :
<?php
$Array=array(
0=>array("name"=>"X","QTY"=>500),
1=>array("name"=>"y","QTY"=>250),
2=>array("name"=>"X","QTY"=>250)
);
?>
Now i want to sum duplicated values as below.
Result :
<?php
$Array=array(
0=>array("name"=>"X","QTY"=>750),
1=>array("name"=>"y","QTY"=>250)
);
?>
UPDATED
i found this function to search in array , foreach and another loops does not works too
<?php
function search($array, $key, $value)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
?>
<?php
$Array=array(
0=>array("name"=>"X","QTY"=>500),
1=>array("name"=>"y","QTY"=>250),
2=>array("name"=>"X","QTY"=>250)
);
$result = array();
$names = array_column($Array, 'name');
$QTYs = array_column($Array, 'QTY');
$unique_names = array_unique($names);
foreach ($unique_names as $name){
$this_keys = array_keys($names, $name);
$qty = array_sum(array_intersect_key($QTYs, array_combine($this_keys, $this_keys)));
$result[] = array("name"=>$name,"QTY"=>$qty);
}
var_export($result); :
array (
0 =>
array (
'name' => 'X',
'QTY' => 750,
),
1 =>
array (
'name' => 'y',
'QTY' => 250,
),
)
Try this simplest one, Hope this will be helpful.
Try this code snippet here
$result=array();
foreach ($Array as $value)
{
if(isset($result[$value["name"]]))
{
$result[$value["name"]]["QTY"]+=$value["QTY"];
}
else
{
$result[$value["name"]]=$value;
}
}
print_r(array_values($result));
Try this, check the live demo.
<?php
$Array=array(
0=>array("name"=>"X","QTY"=>500),
1=>array("name"=>"y","QTY"=>250),
2=>array("name"=>"X","QTY"=>250)
);
$keys = array_column($Array, 'name');
$QTYs = array_column($Array, 'QTY');
$result = [];
foreach($keys as $k => $v)
{
$result[$v] += $QTYs[$k];
}
print_r($result);
You can achieve this by creating an array with name as key and then iterating over all values and add them together, resulting in this
function sum_same($array) {
$keyArray = [];
foreach ($array as $entry) {
$name = $entry["name"];
if(isset($keyArray[$name])) {
$keyArray[$name] += $entry["QTY"];
} else {
$keyArray[$name] = $entry["QTY"];
}
}
// Convert the keyArray to the old format.
$resultArray = [];
foreach ($keyArray as $key => $value) {
$resultArray[] = ["name" => $key, "QTY" => $value];
}
return $resultArray;
}
Try the code here
If you want to alter the old array use the function like this:
$myArray = sum_same($myArray);
The old array will be overwritten by the new one.
This problem is a classic example of usage for array_reduce():
$Array = array(
0 => array('name' => 'X', 'QTY' => 500),
1 => array('name' => 'y', 'QTY' => 250),
2 => array('name' => 'X', 'QTY' => 250),
);
// array_values() gets rid of the keys of the array produced by array_reduce()
// they were needed by the callback to easily identify the items in the array during processing
$Array = array_values(array_reduce(
$Array,
function (array $a, array $v) {
$k = $v['name'];
// Check if another entry having the same name was already processed
// Keep them in the accumulator indexed by name
if (! array_key_exists($k, $a)) {
$a[$k] = $v; // This is the first entry with this name
} else {
// Not the first one; update the quantity
$a[$k]['QTY'] += $v['QTY'];
}
return $a; // return the partial accumulator
},
array() // start with an empty array as accumulator
));

PHP update quantity in multidimensional array

My array looks like the following:
Array
(
[0] => Array
(
[index] => 0
[quantity] => 1
[0] => Array
(
[id_product] => 20
[title] => Oranges
)
)
[1] => Array
(
[index] => 1
[quantity] => 1
[0] => Array
(
[id_product] => 24
[title] => Bananas
)
)
)
To make this array, this is my code:
$i = 0;
$content = array();
if(isset($_SESSION['cart'])){
foreach($_SESSION['cart'] as $result){
foreach($result as $item){
$values = $product->getById($item['id']);
if($values != null){ // which means it has product
/*
Checks if the array already contains that ID
this avoids duplicated products
*/
if(main::search_multidimensional($content, "id_product", $item['id_product']) == null){
$content[] = array("index" => $i, "quantity" => 1, $values);
$i++;
}else{ /*
in case it does have already the id_product in the array
I should update the "quantity" according to the "index".
*/
}
}
}
}
}
return $content;
My problem is after the }else{. I've been trying some codes without any success. I have to update the quantity according to the index. Although if you guys think there's a better alternative please let me know.
Edit: Since most of the people is worried about the search_multidimensional and it might be my solution, here's the function:
public function search_multidimensional($array, $key, $value){
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, self::search_multidimensional($subarray, $key, $value));
}
}
return $results;
}
EDIT 2:
In that case, would this help? (Since your search_multidimensional only returns a true or false)
$i = 0;
$content = array();
if(isset($_SESSION['cart'])){
foreach($_SESSION['cart'] as $result){
foreach($result as $item){
$values = $product->getById($item['id']);
if($values != null) { // which means it has product
/*
Checks if the array already contains that ID
this avoids duplicated products
*/
$product_exists = false;
foreach($content as &$cItem) {
if($cItem['values']['id_product'] == $item['id_product']) {
$cItem['values']['quantity']++; // Increments the quantity by 1
$product_exists = true;
break;
}
}
// If the product does not exist in $content, add it in.
if(!$product_exists)
$content[] = array("index" => $i, "quantity" => 1, "values" => $values);
$i++;
}
}
}
}
(Edited again to give an array key to $values)
OLD ANSWER:
Since you are recreating the cart array in $content, you could just do this in your else:
$content[] = array("index" => $i, "quantity" => $result['quantity'] + 1, $values);
Such that it would show like this:
$i = 0;
$content = array();
if(isset($_SESSION['cart'])){
foreach($_SESSION['cart'] as $result){
foreach($result as $item){
$values = $product->getById($item['id']);
if($values != null){ // which means it has product
/*
Checks if the array already contains that ID
this avoids duplicated products
*/
if(main::search_multidimensional($content, "id_product", $item['id_product']) == null)
$content[] = array("index" => $i, "quantity" => 1, $values);
else
$content[] = array("index" => $i, "quantity" => $result['quantity'] + 1, $values); // Retrieve current quantity and adds 1
$i++;
}
}
}
}
(I'm assuming you are only increasing the quantity by 1)
Solved.
All I had to do was to forget the $i variable, since it wasn't actually doing something necessary. Since I have id_product, which is unique I need to work with it.
if($values != null){ // Only if it has results
// checks if array already contains or not the product ID
// if does not have, it will add
if(global_::search_multidimensional($content, "id_product", $item['id_product']) == null){
$content[] = array("index" => $item['id_product'], "quantity" => 1, $values);
// index is now the id of the product
}else{
// otherwise, loop all the elements and add +1
foreach($content as $key => $result){
if($item['id_product'] == $content[$key]['index']){
$content[$key]['quantity']++;
}
}
}
}
As your $content array has fixed structure (fixed number of levels) you don't need to use recursive function. Your search_multidimensional function could be much simpler. And it should return index of found element (if any) in the array:
function search_multidimensional($array, $key, $value) {
foreach ($array as $i => $el) {
foreach ($el as $j => $v) {
if (is_int($j) && isset($v[$key]) && $v[$key] == $value) return $i;
}
}
return false;
}
So the snippet building $content should be changed like this:
...
if (($index = search_multidimensional($content, "id_product", $item['id_product'])) === false) {
$content[] = array("index" => $i, "quantity" => 1, $values); $i++;
}
else {
$content[$index]['quantity']++;
}

Check if specific array key exists in multidimensional array - PHP

I have a multidimensional array e.g. (this can be many levels deep):
$array = Array (
[21] => Array ( )
[24] => Array (
[22] => Array ( )
[25] => Array (
[26] => Array ( )
)
)
)
I am trying to loop through it to see if a certain key exists:
$keySearch = 22; // key searching for
function findKey($array, $keySearch) {
foreach ($array as $item){
if (isset($item[$keySearch]) && false === findKey($item[$keySearch], $item)){
echo 'yes, it exists';
}
}
}
findKey($array, $keySearch);
But it finds nothing. Is there an error in the loop?
array_key_exists() is helpful.
Then something like this:
function multiKeyExists(array $arr, $key) {
// is in base array?
if (array_key_exists($key, $arr)) {
return true;
}
// check arrays contained in this array
foreach ($arr as $element) {
if (is_array($element)) {
if (multiKeyExists($element, $key)) {
return true;
}
}
}
return false;
}
Working example: http://codepad.org/GU0qG5su
I played with your code to get it working :
function findKey($array, $keySearch)
{
foreach ($array as $key => $item) {
if ($key == $keySearch) {
echo 'yes, it exists';
return true;
} elseif (is_array($item) && findKey($item, $keySearch)) {
return true;
}
}
return false;
}
Here is a one line solution:
echo strpos(json_encode($array), $key) > 0 ? "found" : "not found";
This converts the array to a string containing the JSON equivalent, then it uses that string as the haystack argument of the strpos() function and it uses $key as the needle argument ($key is the value to find in the JSON string).
It can be helpful to do this to see the converted string: echo json_encode($array);
Be sure to enclose the needle argument in single quotes then double quotes because the name portion of the name/value pair in the JSON string will appear with double quotes around it. For instance, if looking for 22 in the array below then $key = '"22"' will give the correct result of not found in this array:
$array =
Array (
21 => Array ( ),
24 =>
Array (
522 => Array ( ),
25 =>
Array (
26 => Array ( )
)
)
);
However, if the single quotes are left off, as in $key = "22" then an incorrect result of found will result for the array above.
EDIT: A further improvement would be to search for $key = '"22":'; just incase a value of "22" exists in the array. ie. 27 => "22" In addition, this approach is not bullet proof. An incorrect found could result if any of the array's values contain the string '"22":'
function findKey($array, $keySearch)
{
// check if it's even an array
if (!is_array($array)) return false;
// key exists
if (array_key_exists($keySearch, $array)) return true;
// key isn't in this array, go deeper
foreach($array as $key => $val)
{
// return true if it's found
if (findKey($val, $keySearch)) return true;
}
return false;
}
// test
$array = Array (
21 => Array ( 24 => 'ok' ),
24 => Array (
22 => Array ( 29 => 'ok' ),
25 => Array (
26 => Array ( 32 => 'ok' )
)
)
);
$findKeys = Array(21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
foreach ($findKeys as $key)
{
echo (findKey($array, $key)) ? 'found ' : 'not found ';
echo $key.'<br>';
}
returns false if doesn't exists, returns the first instance if does;
function searchArray( array $array, $search )
{
while( $array ) {
if( isset( $array[ $search ] ) ) return $array[ $search ];
$segment = array_shift( $array );
if( is_array( $segment ) ) {
if( $return = searchArray( $segment, $search ) ) return $return;
}
}
}
return false;
}
For sure some errors, is this roughly what you are after? (Untested code):
$keySearch=22; // key seraching for
function findKey($array, $keySearch)
{
// check whether input is an array
if(is_array($array)
{
foreach ($array as $item)
{
if (isset($item[$keySearch]) || findKey($item, $keysearch) === true)
{
echo 'yes, it exists';
return true;
}
}
}
}
Here is one solution that finds and return the value of the key in any dimension array..
function findValByKey($arr , $keySearch){
$out = null;
if (is_array($arr)){
if (array_key_exists($keySearch, $arr)){
$out = $arr[$keySearch];
}else{
foreach ($arr as $key => $value){
if ($out = self::findValByKey($value, $keySearch)){
break;
}
}
}
}
return $out;
}
I did modified to return value of searched key:
function findKeyInArray($array, $keySearch, &$value)
{
foreach ($array as $key => $item) {
if ($key === $keySearch) {
$value = $item;
break;
} elseif (is_array($item)) {
findKeyInArray($item, $keySearch,$value);
}
}
}
$timeZone = null;
findKeyInArray($request, 'timezone', $timeZone);

Foreach: Get All The Keys That Have The Value "X"

Suppose I have an array like this:
$array = array("a","b","c","d","a","a");
and I want to get all the keys that have the value "a".
I know I can get them using a while loop:
while ($a = current($array)) {
if ($a == 'a') {
echo key($array).',';
}
next($array);
}
How can I get them using a foreach loop instead?
I've tried:
foreach ($array as $a) {
if ($a == 'a') {
echo key($array).',';
}
}
and I got
1,1,1,
as the result.
If you would like all of the keys for a particular value, I would suggest using array_keys, using the optional search_value parameter.
$input = array("Foo" => "X", "Bar" => "X", "Fizz" => "O");
$result = array_keys( $input, "X" );
Where $result becomes
Array (
[0] => Foo
[1] => Bar
)
If you wish to use a foreach, you can iterate through each key/value set, adding the key to a new array collection when its value matches your search:
$array = array("a","b","c","d","a","a");
$keys = array();
foreach ( $array as $key => $value )
$value === "a" && array_push( $keys, $key );
Where $keys becomes
Array (
[0] => 0
[1] => 4
[2] => 5
)
You can use the below to print out keys with specific value
foreach ($array as $key=>$val) {
if ($val == 'a') {
echo $key." ";
}
}
here's a simpler filter.
$query = "a";
$result = array_keys(array_filter($array,
function($element)use($query){
if($element==$query) return true;
}
));
use
foreach($array as $key=>$val)
{
//access the $key as key.
}

Categories