check exist all value every single key in array? - php

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

Related

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']++;
}

Modifying N-dimensional array PHP

how can I add an extra dimesion before each element in N-dimensional array (recursively)? Let's say I have
Array
(
[room] => Array
(
[bed] = Array
(
[material] => wood
)
)
)
And I want to add an extra "[0]" dimension before room, bed and material. (Adding dimension only if the last element is an array). I also want to distinguish, if there already is the extra [0] dimension, so it will not appear twice .. + I don't want to add [0] if the array key is named "#attribute".
I'm trying to figure it out, but I'm really lost. This is what I've got so far..
function normalize_array (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
foreach ($array[0] as $next) {
normalize_array ($next);
}
}
}
but it does not work recursively. Any help will be appreciated. Thanks!
From the documentation of foreach:
In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by reference.
So if you modify your function like this, it works:
function normalize_array (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
foreach ($array[0] as &$next) { // <-- add & here
normalize_array ($next);
}
}
}
Possible solution (tested just a little, but seems to work):
function normalize_array($array, $keys){
$new = array();
foreach($array as $key => $value){
if (in_array($key, $keys) && is_array($value)){
$new["0"] = array($key => normalize_array($value, $keys));
} else {
$new[$key] = $value ;
}
}
return $new ;
}
$data = array(
"room" => array(
"bed" => array(
"material" => "wood"
)
)
);
$keys = array("room", "bed", "material");
$new = normalize_array($data, $keys);
var_dump($new);
Final solution:
function normalize_array_rec (&$array) {
if (is_array($array)) {
if (!isset($array[0])) {
$array = array ( "0" => $array);
}
$i = 0;
while (isset($array[$i])) {
foreach ($array[$i] as &$next) {
normalize_array_rec ($next);
}
$i++;
}
}
}
Forgot to call function in each instance of array, not only in [0] index.

PHP: Count the appearance of particular value in array

I am wondering if I could explain this.
I have a multidimensional array , I would like to get the count of particular value appearing in that array
Below I am showing the snippet of array . I am just checking with the profile_type .
So I am trying to display the count of profile_type in the array
EDIT
Sorry I've forgot mention something, not something its the main thing , I need the count of profile_type==p
Array
(
[0] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => p
[birthyear] => 1978
[is_elite] => 0
)
)
[1] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => d
[birthyear] => 1972
[is_elite] => 1
)
)
)
Easy solution with RecursiveArrayIterator, so you don't have to care about the dimensions:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$counter = 0
foreach ($iterator as $key => $value) {
if ($key == 'profile_type' && $value == 'p') {
$counter++;
}
}
echo $counter;
Something like this might work...
$counts = array();
foreach ($array as $key=>$val) {
foreach ($innerArray as $driver=>$arr) {
$counts[] = $arr['profile_type'];
}
}
$solution = array_count_values($counts);
I'd do something like:
$profile = array();
foreach($array as $elem) {
if (isset($elem['Driver']['profile_type'])) {
$profile[$elem['Driver']['profile_type']]++;
} else {
$profile[$elem['Driver']['profile_type']] = 1;
}
}
print_r($profile);
You may also use array_walk($array,"test") and define a function "test" that checks each item of the array for 'type' and calls recursively array_walk($arrayElement,"test") for items of type 'array' , else checks for the condition. If condition satisfies, increment a count.
Hi You can get count of profuke_type==p from a multi dimensiona array
$arr = array();
$arr[0]['Driver']['id'] = 4;
$arr[0]['Driver']['profile_type'] = 'p';
$arr[0]['Driver']['birthyear'] = 1978;
$arr[0]['Driver']['is_elite'] = 0;
$arr[1]['Driver']['id'] = 4;
$arr[1]['Driver']['profile_type'] = 'd';
$arr[1]['Driver']['birthyear'] = 1972;
$arr[1]['Driver']['is_elite'] = 1;
$arr[2]['profile_type'] = 'p';
$result = 0;
get_count($arr, 'profile_type', 'd' , $result);
echo $result;
function get_count($array, $key, $value , &$result){
if(!is_array($array)){
return;
}
if($array[$key] == $value){
$result++;
}
foreach($array AS $arr){
get_count($arr, $key, $value , $result);
}
}
try this..
thanks

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.
}

How to find an array from parent array?

I am using below code to find an array inside parent array but it is not working that is retuning empty even though the specified key exits in the parent array
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $cards_parent[$key];
break;
}
}
Do you know any array function that will search parent array for specified key and if found it will create an array starting from that key?
you want array_key_exists()
takes in a needle (string), then haystack (array) and returns true or false.
in one of the comments, there is a recursive solution that looks like it might be more like what you want. http://us2.php.net/manual/en/function.array-key-exists.php#94601
here you can use recursion:
function Recursor($arr)
{
if(is_array($arr))
{
foreach($arr as $k=>$v)
{
if($k == 'Cards')
{
$_GLOBAL['cards'][] = $card;
} else {
Recursor($arr[$k]);
}
}
}
}
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$_GLOBAL['cards'] = array();
Recursor($cards_parent);
Could you please put a print_r($feedData) up? I ran the below code
<?php
$feedData = array('BetradarLivescoreData' => array('Sport' => array('Category' => array('Tournament' => array('Match' => array('Cards' => array('hellow','jwalk')))))));
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $card;
break;
}
}
print_r($cards);
And it returned a populated array:
Array ( [0] => Array ( [0] => hellow [1] => jwalk ) )
So your code is correct, it may be that your array $feedData is not.

Categories