Check if all of the values of a multidimensionnal array is null - php

I've a multidimensionnal array like that, and I wan't to check if all of the "open_at" and "closed_at" values are NULL.
array:7 [▼
0 => array:2 [▼
0 => array:2 [▼
"open_at" => null
"closed_at" => "11:03"
]
1 => array:2 [▼
"open_at" => "13:00"
"closed_at" => "16:00"
]
]
1 => array:2 [▼
0 => array:2 [▼
"open_at" => "09:00"
"closed_at" => "12:00"
]
1 => array:2 [▼
"open_at" => "12:30"
"closed_at" => "17:00"
]
]
2 => array:2 [▼
0 => array:2 [▼
"open_at" => "08:00"
"closed_at" => "18:00"
]
1 => array:2 [▼
"open_at" => null
"closed_at" => null
]
]
3 => array:2 [▼
0 => array:2 [▼
"open_at" => null
"closed_at" => null
]
1 => array:2 [▼
"open_at" => null
"closed_at" => null
]
]
...
I've tried with multiple for and foreach loop like, with no success...
for ( $i = 0; $i <6 ; $i++) {
for ($j = 0; $j < 2; $j++) {
if(empty($hours[$i][$j]["open_at"])){
$null="complete";
}
else{
$null="empty";
}
return $null;
}
}
The array should be checked as empty only if all the "open_at" and "closed_at" values are set to NULL.
As saw in the example above, the first values can be set to NULL, but the array should not be checked as empty in that case.
The goal is to don't execute the code bellow only if all the "open_at" and "closed_at" are set to NULL.
$hours = $request->get('hours');
//check if empty here
foreach ($hours as $key => $period) {
foreach($period as $attribute => $value){
$shops_hour = new Shops_hour();
$shops_hour->shop_id=$shop->id;
$shops_hour->day=$key;
$shops_hour->period=$attribute;
$shops_hour->open_at=$hours[$key][$attribute]["open_at"];
$shops_hour->closed_at=$hours[$key][$attribute]["closed_at"];
$shops_hour->save();
}
}
Thank you in advance,

Using a recursive function that will return true if all values contained are null:
function all_null_recursive($arr)
{
foreach ($arr as $item) {
/* if the item is an array
and the function itself found something different from null */
if (is_array($item) && all_null_recursive($item) === false) {
return false;
// if the item is not an array and different from null
} elseif (!is_array($item) && $item !== null) {
return false;
}
}
// always found null, everything's good
return true;
}
Testing:
The 2 arrays to test with.
$foo = [
0 => [
0 => [
"open_at" => null,
"closed_at" => "11:03"
],
1 => [
"open_at" => "13:00",
"closed_at" => "16:00"
],
],
1 => [
0 => [
"open_at" => "09:00",
"closed_at" => "12:00"
],
1 => [
"open_at" => "12:30",
"closed_at" => "17:00"
],
],
2 => [
0 => [
"open_at" => "08:00",
"closed_at" => "18:00"
],
1 => [
"open_at" => null,
"closed_at" => null
],
],
3 => [
0 => [
"open_at" => null,
"closed_at" => null
],
1 => [
"open_at" => null,
"closed_at" => null
]
]
];
$foo_2 = [
0 => [
0 => [
"open_at" => null,
"closed_at" => null
],
1 => [
"open_at" => null,
"closed_at" => null
],
],
1 => [
0 => [
"open_at" => null,
"closed_at" => null
],
1 => [
"open_at" => null,
"closed_at" => null
],
],
2 => [
0 => [
"open_at" => null,
"closed_at" => null
],
1 => [
"open_at" => null,
"closed_at" => null
],
],
3 => [
0 => [
"open_at" => null,
"closed_at" => null
],
1 => [
"open_at" => null,
"closed_at" => null
]
]
];
Testing:
var_dump(all_null_recursive($foo)); // bool(false)
var_dump(all_null_recursive($foo_2)); // bool(true)

The #jeff method work, thank you
$foundOneWithaValue = "0";
foreach ($hours as $key => $period) {
foreach($period as $attribute => $value){
if(!empty($hours[$key][$attribute]["open_at"]) || (!empty($hours[$key][$attribute]["closed_at"])) ) {
$foundOneWithaValue ++;
}
}
}
if($foundOneWithaValue != 0)
{
foreach ($hours as $key => $period) {
foreach($period as $attribute => $value){
$shops_hour = new Shops_hour();
$shops_hour->shop_id=$shop->id;
$shops_hour->day=$key;
$shops_hour->period=$attribute;
$shops_hour->open_at=$hours[$key][$attribute]["open_at"];
$shops_hour->closed_at=$hours[$key][$attribute]["closed_at"];
$shops_hour->save();
}
}
}

Related

recursive function transform nested array

Im my laravel project I have this nested array that needs to be updated (transformed - for the frontend):
array:2 [
0 => array:3 [
"entity_id" => 931
"entity" => "user"
"children" => array:2 [
0 => array:2 [
"entity_id" => 5
"entity" => "location"
]
1 => array:2 [
"entity_id" => 932
"entity" => "user"
]
]
]
1 => array:2 [
"entity_id" => 486
"entity" => "user"
]
]
EXPECTED ARRAY:
array:2 [
0 => array:4 [
"id" => 931
"text" => "Test User 1"
"type" => "user"
"children" => array:2 [
0 => array:3 [
"id" => 5
"text" => "Location 1"
"type" => "location"
]
1 => array:3 [
"id" => 932
"text" => "Test User 2"
"type" => "user"
]
]
]
1 => array:3 [
"id" => 486
"text" => "Test User 3"
"type" => "user"
]
]
I have created a recursive function for this job
public function getNewStructure($tree, &$output) {
foreach($tree as $data) {
$output[] = array(
'id' => $data['entity_id'],
'text' => $data['user'] === 'user' ? User::find($data['entity_id'])->name : Location::find($data['entity_id'])->name,
'type' => $data['entity']
);
$this->getNewStructure($data['children'] ?? [], $output);
}
return $output;
}
but it not returns as expected:
array:4 [
0 => array:3 [
"id" => 931
"text" => "Test User 1"
"type" => "user"
]
0 => array:3 [
"id" => 5
"text" => "Location 1"
"type" => "location"
]
1 => array:3 [
"id" => 932
"text" => "Test User 2"
"type" => "user"
]
1 => array:3 [
"id" => 486
"text" => "Test User 3"
"type" => "user"
]
]
How can I add the children to the $output array in the recursive function ???
I have tried by adding the children key:
$this->getNewStructure($data['children'] ?? [], $output['children']);
as when iterating again it will push the current array in the right place.... but is not working...
I fixed
public function getNewStructure($tree, &$output) {
foreach($tree as $data) {
$element = array(
'id' => $data['entity_id'],
'text' => $data['user'] === 'user' ? User::find($data['entity_id'])->name : Location::find($data['entity_id'])->name,
'type' => $data['entity']
);
if(is_array($data['children']) && count($data['children']) > 0) {
$element['children'] = $this->getNewStructure($data['children'], $element['children']);
}
$output[] = $element;
}
return $output;
}

How to validate array object in Laravel with?

I have this JSON array list and want to validate to ensure min_distance and max_distance in array 0 are ways less than array 1... and vice-versa
array:2 [
"name" => "Run"
"pricing" => array:3 [
0 => array:3 [
"min_distance" => "1.0000"
"max_distance" => "2.0000"
"assign" => "8.0000"
]
1 => array:3 [
"min_distance" => "3.0000"
"max_distance" => "4.0000"
"assign" => "2.0000"
]
2 => array:3 [
"min_distance" => "4.0000"
"max_distance" => "5.0000"
"assign" => "50.0000"
]
]
]
You can do like this:
if($arr['pricing'][0]['min_distance'] > $arr['pricing'][1]['min_distance'] || $arr['pricing'][0]['max_distance'] > $arr['pricing'][1]['max_distance']) {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
and in your view:
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif

re-index array and add totals

I'm trying to figure out how to restructure an array and total values by given keys. I currently have an array called $data that is returning this result:
Bill => array:3 [▼
"01" => array:6 [▼
"Food " => array:2 [▶]
hamburger=>array:[
sales=> 210.00
purchases=>200.00
]
burrito=>array:[
sales=> 100.00
purchases=>40.00
]
"Drink " => array:2 [▶]
coke=>array:[
sales=> 210.00
purchases=>200.00
]
pepsi=>array:[
sales=> 100.00
purchases=>40.00
]
"total" => array:7 [▶]
sales=>620.00
purchases=>480.00
]
]
Ted => array:3 [▼
"01" => array:6 [▼
"Food " => array:2 [▶]
hamburger=>array:[
sales=> 110.00
purchases=>100.00
]
burrito=>array:[
sales=> 120.00
purchases=>40.00
]
"Drink " => array:2 [▶]
coke=>array:[
sales=> 110.00
purchases=>100.00
]
pepsi=>array:[
sales=> 120.00
purchases=>40.00
]
"total" => array:7 [▶]
sales=>460.00
purchases=>280.00
]
]
My issue is that I need to fit this into a laravel blade that is not concerned with bill or ted, but rather totals for everyone. Where the existing keys are "Bill" and "Ted", I would need the new structure to actually be identified by the "01", but I want to total all of the categories within that level. So I would be hoping to get results like this:
"01" =>[▼
"Food " => array:2 [▶]
hamburger=>array:[
sales=> 320.00
purchases=>300.00
]
burrito=>array:[
sales=> 220.00
purchases=>140.00
]
"Drink " => array:2 [▶]
coke=>array:[
sales=> 320.00
purchases=>300.00
]
pepsi=>array:[
sales=> 220.00
purchases=>80.00
]
"total" => array:7 [▶]
sales=>1080.00
purchases=>760.00
]
I can easily loop on this like:
foreach($data as $key=> $value){
foreach($value as $categoryNumber => $categories){
foreach($categories as $categoryDetails => $details){
}
}
}
But I'm completely stuck as to how to re-structure this and total by the new indices
I am not sure how you arrived at the above dd();, I am sure there is a better way of collecting these totals prior to arriving here. But now that you are here (say, you received this via an API or whatever), this would make the totals as you mentioned:
$result = [];
foreach ($input as $i) {
foreach ($i as $group => $n) {
if (!array_key_exists($group, $result)) $result[$group] = [];
foreach ($n as $category_name => $category) {
if (!array_key_exists($category_name, $result[$group])) $result[$group][$category_name] = [];
foreach ($category as $item_name => $item) {
if (!array_key_exists($item_name, $result[$group][$category_name])) {
$result[$group][$category_name][$item_name] = $item;
} else {
foreach ($item as $purpose => $dollars) {
$result[$group][$category_name][$item_name][$purpose] += $dollars;
}
}
}
}
}
}
In each step, I am checking if the array key exists, and if not, creating it. If you ignore those array_key_exists() checks, you'll see that I am simply copying the contents over and summing where necessary.
You do something like this...
<?php
$data = [
'Bill' => [
"01" => [
"Food" => [
'hamburger' => [
'sales' => 210.00,
'purchases' => 200.00,
],
'burrito' => [
'sales' => 100.00,
'purchases' => 40.00,
],
],
"Drink" => [
'coke' => [
'sales' => 210.00,
'purchases' => 200.00,
],
'pepsi' => [
'sales' => 100.00,
'purchases' => 40.00,
],
],
"total" => [
'sales' => 620.00,
'purchases' => 480.00,
],
]
],
'Ted' => [
"01" => [
"Food" => [
'hamburger' => [
'sales' => 110.00,
'purchases' => 100.00,
],
'burrito' => [
'sales' => 120.00,
'purchases' => 40.00,
],
],
"Drink" => [
'coke' => [
'sales' => 110.00,
'purchases' => 100.00,
],
'pepsi' => [
'sales' => 120.00,
'purchases' => 40.00,
],
],
"total" => [
'sales' => 460.00,
'purchases' => 280.00,
],
]
]
];
$finalResults = [];
foreach ($data as $userName => $bills) {
foreach ($bills as $billIndex => $billParts) {
if (!array_key_exists($billIndex, $finalResults)) {
$finalResults[$billIndex] = [
'total' => [
'sales' => 0,
'purchases' => 0,
]
];
}
foreach ($billParts as $partIndex => $details) {
if (!array_key_exists($partIndex, $finalResults[$billIndex])) {
$finalResults[$billIndex][$partIndex] = [];
}
if ($partIndex !== 'total') {
foreach ($details as $productCode => $productData) {
if (!array_key_exists($productCode, $finalResults[$billIndex][$partIndex])) {
$finalResults[$billIndex][$partIndex][$productCode] = [
'sales' => 0,
'purchases' => 0,
];
}
$finalResults[$billIndex][$partIndex][$productCode]['sales'] += $productData['sales'];
$finalResults[$billIndex][$partIndex][$productCode]['purchases'] += $productData['purchases'];
}
} else {
$finalResults[$billIndex][$partIndex]['sales'] += $details['sales'];
$finalResults[$billIndex][$partIndex]['purchases'] += $details['purchases'];
}
}
}
}
print_r($finalResults);

PHP - Add new object to every array of objects

Consider this array of objects in PHP:
array:2 [
0 => array:4 [
"Row_Id" => 256
"Start_Date" => "2020-05-16"
"account_code" => ""
"caller_number" => "452"
]
1 => array:4 [
"Row_Id" => 257
"Start_Date" => "2020-05-16"
"account_code" => ""
"caller_number" => "42"
]
2 => array:4 [
"Row_Id" => 258
"Start_Date" => "2020-05-16"
"account_code" => ""
"caller_number" => "428"
]
]
I want to add "callee_number:100" in every array so my output should look like these:
array:2 [
0 => array:5 [
"Row_Id" => 256
"Start_Date" => "2020-05-16"
"account_code" => ""
"caller_number" => "452"
"callee_number" => "100"
]
1 => array:5 [
"Row_Id" => 257
"Start_Date" => "2020-05-16"
"account_code" => ""
"caller_number" => "42"
"callee_number" => "100"
]
2 => array:5 [
"Row_Id" => 258
"Start_Date" => "2020-05-16"
"account_code" => ""
"caller_number" => "428"
"callee_number" => "100"
]
]
I have taken the above input array in $get variable. Now I am calling array_push to append callee_number to every array:
array_push($get,[
'callee_number':'100'
]);
Also tried using array_merge but callee_number is not getting appended. How can I achieve that ?
Given the following array:
$array = [
[
"Row_Id" => 256,
"Start_Date" => "2020-05-16",
"account_code" => "",
"caller_number" => "452",
],
[
"Row_Id" => 257,
"Start_Date" => "2020-05-16",
"account_code" => "",
"caller_number" => "42",
],
[
"Row_Id" => 258,
"Start_Date" => "2020-05-16",
"account_code" => "",
"caller_number" => "428",
],
];
Native PHP
$array = array_map(function ($item) { return $item + ['callee_number' => 100]; }, $array);
Using collections
$array = collect($array)->map(function ($item) { return $item + ['callee_number' => 100]; })->toArray();
Using PHP 7.4 shorthands
$array = array_map(fn($item) => $item + ['callee_number' => 100], $array);
// Or
$array = collect($array)->map(fn($item) => $item + ['callee_number' => 100])->toArray();
To add or modify an element in each sub-array you would do this:
foreach ($get as &$g) {
$g["callee_number"] = 100;
}
Or this:
for ($c = 0; $c < count($get); $c++) {
$get[$c]["callee_number"] = 100;
}

I have an array with multi-dimension, I want to get the name of the array and the value of array

Problem in splitting array in PHP.
I need pradm_policy_risk_attr_details_motor_id => 20170825113749907.
but in array only. Below is my example how to I needed in array
$array = [pradm_policy_risk_attr_details_motor_id => 20170825113749907,
column_11 => BP-2-B1534,
column_14 => Mahindra];
How can get this?
This is my array
array:19 [
"pradm_policy_risk_attr_details_motor_id" => array:1 [
0 => "20170825113749907"
]
"column_11" => array:1 [
0 => "BP-2-B1534"
]
"column_14" => array:1 [
0 => "Mahindra"
]
"column_15" => array:1 [
0 => "Bolero-Camper 2WD (2523 cc)"
]
"column_61" => array:1 [
0 => ""
]
"column_92" => array:1 [
0 => "0.000000"
]
"column_28" => array:1 [
0 => "[SELECT]"
]
"column_29" => array:1 [
0 => "Closed"
]
"column_30" => array:1 [
0 => "0"
]
"column_32" => array:1 [
0 => "Owner Driver"
]
"column_33" => array:1 [
0 => ""
]
"column_35" => array:1 [
0 => "Excavator"
]
"column_36" => array:1 [
0 => ""
]
"column_69" => array:1 [
0 => ""
]
"column_70" => array:1 [
0 => ""
]
"column_24" => array:1 [
0 => ""
]
"column_16" => array:1 [
0 => "Select"
]
"column_121" => array:1 [
0 => ""
]
"column_122" => array:1 [
0 => ""
]
]
If you need to 'flatten' the whole array, try array_map. The way it works is you define a function, that receives a single array item, transforms it and returns transformed value, then you pass that function to array_map in order to perform said transformation on all elements of the array:
function flatten($item){
return $item[0];
}
$original_array = Array(...); // assign your original array here
$flattened_array = array_map('flatten', $original_array);
Or using anonymous function syntax:
$flattened_array = array_map(function($item){return $item[0]}, $original_array);

Categories