PHP validate array with sub array? - php

I have a PHP array with weekdays, by form submit I get additional data, but I want to validate this array, so if the array is empty a want to show a message, my problem there is always a sub-array called "games" and so is the main array never empty. How can I ignore them?
The "empty" array structure is like:
'monday' = ['games' = [1, 2, 3, 'game_off']],

Iterate the array and count the values for each day. Since there will always be one value for 'games', then look for counts < 2. If any are found, then that item only contains 'games' and your array is invalid.
$valid = true;
foreach ($array as $day => $values) {
if (count($values) < 2) {
$valid = false;
break;
}
}
This will verify that every day has something besides 'games'. If you need to verify that any day has something besides 'games', then the logic is the opposite.
$valid = false;
foreach ($array as $day => $values) {
if (count($values) > 1) {
$valid = true;
break;
}
}

You can walk into array and count them:
$count = 0;
foreach ($array as $item) {
if (is_array($item) && count(item) > 0){
foreach ($item as $key => $subitem) {
if ($key != 'games'){
$count++;
}
}
}
}
if ($count > 0){
//your array is valid
}

Related

Outputting odd and even number in array

Using below array, i'm trying to use foreach loop to iterate through each item. Then i need to apply if condition to check if the given number is even and odd. I also need to create two arrays one for even and one for odd and push each number in their respective category.
So i have done this so far:
These are the two arrays i created to push through the values to.
}
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if (value %2 == 0)
{
$array_even = $value;
echo $array_even;
}
else
{
$array_odd = $value;
echo $array_odd;
}
I'd like to know if i'm using the correct solution or are there major errors im committing?
It will surely work like charms.
$numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14];
$array_odd = [];
$array_even = [];
foreach ($numbers as $value)
{
if ($value %2 == 0)
{
$array_even[] = $value;
}
else
{
$array_odd[] = $value;
}
}
echo "<pre>";
print_r($array_odd);
echo "<pre>";
print_r($array_even);

how to insert array 2d in table mysql with php if sub array diferent

i will ask how to insert array if amount sub arrays not same, i have problem if the $arrays != 3 because in sub arrays 2 in arrays one
<?php
$arrays=array(
array('a','b'),
array('a','b','c'),
array('a','b','c')
);
$per=0;
for ($h=0; $h < count($arrays); $h++) {
if (count($arrays) > $per) {
$per= count($arrays);
}
}
$koneksi = new mysqli("127.0.0.1","root","","data");
$nil=array();
foreach ($arrays as $data) {
foreach ($data as $key => $value) {
$data[$key] = $data[$key];
}
$nil[]="('".implode("', '",$data). "')";
}
$insert="INSERT INTO datams (data1,data2,data3) VALUES ".implode(', ',$nil);
$queri=mysqli_query($koneksi, $insert);
if ($queri == true){
echo 'upload done'.PHP_EOL;
} else {
echo 'fail upload'.PHP_EOL;
}
i can't insert the data if sub array same, can help me ?
You will have to make the arrays the same length.
Create an empty array, then loop your existing array, adding the missing values using array_replace. After that, you can insert them.
$empty=['' , '' , ''];
foreach($array as $key => $tmp){
$array[$key] = array_replace($empty,$tmp);
// This replaces the values of $empty with those of $array that are set:
// ['','',''] replace wihh ['a','b','c'] gives ['a','b','c']
// ['','',''] replace with ['a','b'] gives ['a','b','']
}
You will end up with:
$arrays=array(
array('a','b','' ),
array('a','b','c'),
array('a','b','c')
);
Now you can insert the values;
EDIT
To make it more flexible (i.e the original array keeps changing), you first have to find the length of the longest array in $array.
$max=0;
foreach($array as $a) {
$c = count($a);
if( $c > $max) $max = $c;
}
$empty=array_fill(0,$max,'');

Incrementing value of an array from another array

I have 2 arrays
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
Now I need to search in $array2 for id from $array1 and if found to increment the count value and also add to the array the one's which are not found with a count as 1 so my resulting array would be
$arr = array(array('id'=>22, 'count'=> 2), array('id'=>124, 'count'=>3), array('id'=>193, 'count'=>1));
any help would be appreciated
The current code which I tried is
if($array2){
foreach($array1 as $array){
if(in_array($array, array_column($array2, 'id'))){
$wa_array['count'] += 1;
} else {
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
} else {
foreach($array1 as $array){
$wa_array['id'] = $array;
$wa_array['count'] = 1;
}
}
This may be something you are looking for -
$array1 = array(22,193,124);
$array2 = array(array('id'=>22, 'count'=> 1), array('id'=>124, 'count'=>2));
foreach($array1 as $key=>$digit)
{
$keyFound = array_search($digit, array_column($array2, 'id'));
if($keyFound === false)
{
array_push($array2, ['id'=>$digit, 'count'=>1]);
}
else
{
$array2[$keyFound]['count']++;
}
}
print_r($array2);
The question is not so clear, so I will go with my understanding : You need to check if values inside the first array are in the second array. If yes, increment the count value of that second array, if not, create that element with the value of 1.
This code is not tested, hope this can help find the good solution.
foreach($array1 as $value){
searchForId($value,$array2);
}
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['id'] === $id) {
$val['count'] += 1;
}else{
array_push(array('id'=>$id,'count'=>1))
}
}
return null;
}
you should loop through $array2, not $array1. Finding the value in array_column($array2, 'id') doesn't tell you the index of the array element to increment.
foreach ($array2 as &$item) {
if (in_array($item['id'], $array1)) {
$item['count']++;
}
}
Note that you have to use &$item to make this a reference to the original array element, so that modifying it will update $array2. Otherwise, $item would be a copy of the array element.
If $array1 is large, it would be better to convert it to an associative array so you can test membership more efficiently.
$array1_assoc = array_flip($array1);
Then the test in the loop becomes:
if (isset($array1_assoc[$item['id']]) {
Check this one. NOTE: But this has O(n^2) complexity.
$array1 = [22,193,124];
$array2 = [['id'=>22, 'count'=> 1], ['id'=>124, 'count'=>2]];
foreach ($array1 as $value) {
$isFound = false;
foreach ($array2 as &$item) {
if ($value == $item['id']) {
$item['count']++;
$isFound = true;
continue;
}
}
if ($isFound == false) {
$array2 [] = ['id'=>$value, 'count'=> 1];
}
}
var_dump($array2);

Change the index of an array

I need help to change the index of an array.
I have this array:
$items = array('items' => array(
0 => array(
'item_id' => 1,
'item_amount' => 100,
),
1 => array(),
));
Now I want to remove the index, based on the value of item_id, but I don't know how to do this.
I've tried to do it as follows, but doesn't work.
foreach($items['items'] as $key) {
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($removeIndex);
}
}
How can I do this?
You need to use unset like this:
foreach($items['items'] as $index => $key) { // also get the index!
if (!isset($key['item_id'])) continue; // skip
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($items['items'][$index]['item_id']); // specify path to that entry
}
}
See it run on eval.in.
To unset something in your nested array structure, you need to act on that array itself. unset($removeIndex) does not change the array, because that is a boolean value.
The extra if is there for the case when you don't have an item_id in some sub-array: in that case that iteration of the loop is skipped.
Removing the entire "row"
If your aim is to also remove the sub-array to which the item_id belongs (so including the item_amount and any other value in that sub-array), then just shorten the "path" in the unset statement:
foreach($items['items'] as $index => $key) { // also get the index!
if (!isset($key['item_id'])) continue; // skip
$removeIndex = $key['item_id'] == 1;
if($removeIndex) {
unset($items['items'][$index]); // specify path to that entry
}
}
See it run on eval.in.
You need to call unset($items['items'][0]). For your case it will be something like this:
$id = 1;
$keyToRemove = false;
foreach ($items['items'] as $key => $value) {
if ($value['item_id'] == $id) {
$keyToRemove = $key;
break;
};
}
if ($keyToRemove) {
unset($items['items'][$keyToRemove]);
}
If you want to remove the specific entry 'item_id' in the $items array, you have to refer to it and use both keys, like in:
foreach($items['items'] as $key => $val) {
if (!isset($val['item_id'])) continue;
$removeIndex = $val['item_id'] == 1;
if($removeIndex)
unset($items['items'][$key]);
}
If you downvote, please state why you think this answer is not appropriate.

Two arrays: if a key in the first array is empty, set the same key in the second array to be empty?

I have this array that has two $rows:
I'd like the second array's display to be based on the first array but I don't think I have it set up properly:
$rows = &$vars['rows'];
foreach ($rows[0] as $key => $value) {
if (strpos($key, 'views') === 0 && empty($value)) {
$rows[1][$key] = '';
unset($vars['header'][$key]);
}
}
This is the output from the code, you can see the table doesn't seem aligned properly:
You need to loop over the whole array and then loop over the inner data as well. Simply you need two foreach loops.
$rows = $vars;
foreach ($rows as $occ => $outer ) {
foreach ($outer as $key => $value) {
if (strpos($key, 'views') === 0 && $value =='') {
unset($vars[$occ][$key]);
}
}
}

Categories