remove empty child array from array - laravel

I have a problem which is that I have a array and in this array also a sub array I want to delete the sub-array that do not contain any values instead of the [] to null

This recursive function should do the trick... will only touch empty arrays
<?php
function emptyArraysToNull(&$object){
if(is_array($object))
foreach ($object as $key => &$value) {
if (is_array($value)) {
$value = emptyArraysToNull($value);
}
if (empty($value)) {
$object[$key] = null;
}
}
return $object;
}
// TEST
$very_nested_array = [
[
"name" => "test",
"id" => 1,
"districts" => [
"id" => 2,
"districts" => [],
"test" => []
]
],
[
"id" => []
]
];
print_r(emptyArraysToNull($very_nested_array));
Output:
array(2) {
[0]=>
array(3) {
["name"]=>
string(4) "test"
["id"]=>
int(1)
["districts"]=>
array(3) {
["id"]=>
int(2)
["districts"]=>
NULL
["test"]=>
NULL
}
}
[1]=>
array(1) {
["id"]=>
NULL
}
}
Live demo: http://sandbox.onlinephpfunctions.com/code/4644ec81b623d9cd0c79e1aa67ab55a64cd9416d

Related

How to get the size of an array in document using MongoDB Laravel Query

i have the data
{
"_id": {
"$oid": "5e8e1be5a78b4479443eae43"
},
"vehicle_component_id": 3,
"damages_types": [
1,
7
],
"mileages": [
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0",
"0"
],
"damages": {
"1": {
"upper_bound": [
null
],
"damages": [
"0"
],
"lower_bound": [
null
]
},
"7": {
"upper_bound": [
null
],
"damages": [
"0"
],
"lower_bound": [
null
]
}
},
"created_at": "2020-04-08 20:45:57",
"updated_at": "2020-04-08 20:45:57"
}
and trying to get the size or length of the mileages array the mongo query is
db.vehicle_component_damages_values.aggregate(
{ $match: { vehicle_component_id: 3} },
{$project: { count: { $size:"$mileages" }}}
)
and it's returning 10 as expected but when trying with jenssegers/laravel-mongodb like
$query = DB::connection($this->mongoCon)->collection($this->table)->raw(function($collection) use ($vehicleComponentId) {
return $collection->aggregate([
['$match' => ['vehicle_component_id' => $vehicleComponentId]],
[
'$project' => [
'count' => [
'$size' => '$mileages'
]
]
],
]);
});
it's returning
MongoDB\Driver\Cursor {#550}
so my final code for this is
public function findMileagesSizeByVehicleComponentId($vehicleComponentId)
{
try {
$cursor = DB::connection($this->mongoCon)->collection($this->table)->raw(function ($collection) use (
$vehicleComponentId
) {
return $collection->aggregate([
['$match' => ['vehicle_component_id' => $vehicleComponentId]],
[
'$project' => [
'count' => [
'$size' => '$mileages',
],
],
],
]);
});
$result = $cursor->toArray();
if (!empty($result)) {
if (sizeof($result) == 1) {
return iterator_to_array($result[0])['count'];
} else {
throw new ValidationError("Result has multiple counts please check your query.");
}
} else {
return 0;
}
} catch (\Throwable $e) {
return Error::handel($e);
} catch (\Exception $e) {
return Error::handel($e);
}
}

How to validate multiple input with the same name in a class extended from FormRequest

I'm new to Laravel.
I want to know how to validate multiple input with the same name.
I have a validation rule for a POST request but this fails the validation although I have all values required.
I noticed that the key names are not the same as the key names from user input, so I think that's causing the problem.
On the page I have a form like this, so, I have many input fields with the name like "visit[0]['did_visit']", "visit[1]['did_visit']", "visit[2]['did_visit']...
But, I can't figure out how to validate these on my class extended from FormRequest class.
Please help me!!
VisitRecordRequest extends FormRequest
class VisitRecordRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
switch($this->method())
{
case 'GET':
return [];
case 'POST':
{
//var_dump my input!!!
echo "<pre>";
var_dump($this->input());
echo "</pre>";
exit;
return [
'date' => 'required',
'hour' => 'required',
'minute' => 'required',
'weather' => 'required',
'room_id' => 'required',
'did_visit' => 'required',
'bounce_zone' => 'required',
'bounce_reason' => 'required',
'next_action' => 'required',
];
}
case 'PUT':
{
return [];
}
case 'PATCH':
{
return [];
}
case 'DELETE':
{
return [];
}
default:break;
}
return [];
}
public function response(array $errors)
{
}
}
var_dump log
array(2) {
["visit"]=>
array(3) {
["common"]=>
array(4) {
["date"]=>
string(10) "2017-05-13"
["hour"]=>
string(2) "09"
["minute"]=>
string(2) "00"
["weather"]=>
string(5) "sunny"
}
[0]=>
array(6) {
["room_id"]=>
string(2) "33"
["did_visit"]=>
string(2) "on"
["bounce_zone"]=>
string(1) "1"
["bounce_reason"]=>
string(1) "1"
["next_action"]=>
string(1) "2"
["memo"]=>
string(11) "hello world"
}
[1]=>
array(6) {
["room_id"]=>
string(2) "34"
["did_visit"]=>
string(3) "off"
["bounce_zone"]=>
string(1) "0"
["bounce_reason"]=>
string(1) "0"
["next_action"]=>
string(1) "1"
["memo"]=>
string(14) "hello world!!!"
},
[2]=>
array(6) {
["room_id"]=>
string(2) "35"
["did_visit"]=>
string(3) "off"
["bounce_zone"]=>
string(1) "3"
["bounce_reason"]=>
string(1) "2"
["next_action"]=>
string(1) "1"
["memo"]=>
string(14) "hello world!!!"
}
}
["_token"]=>
string(40) "2yvZEmM3SUxTcUAZusZs87B1fKD4edVFy0AY4kjC"
}
'visit.*.did_visit' => 'required'
Check here for more info https://laravel.com/docs/5.4/validation#validating-arrays
it should be visit => 'array' .. then have a separate validator for visit ..
then have
foreach($request->visit as $visit)
{
//validate visit ..
}

Merge results of query

I have a query that outputs its values as json in the following format:
[
{
"name":"Bob",
"date":"2016-02-05 00:00:00",
"value":34
},
{
"name":"John",
"date":"2016-02-05 00:00:00",
"value":5
},
{
"name":"Bob",
"date":"2016-02-05 00:00:00",
"value":3
},
{
"name":"Sarah",
"date":"2016-02-05 00:00:00",
"value":56
}
...
]
I need to put this data into the form:
[
{
"name":"Bob",
"data": [
[2016-02-05 00:00:00, 34],
[2016-02-05 00:00:00, 3]
]
},
{
"name":"John",
"data": [
[2016-02-05 00:00:00, 5]
]
},
{
"name":"Sarah",
"data": [
[2016-02-05 00:00:00, 56]
]
}
...
]
Or in other words, I need to combine the results that share a name and put the data into an array data, where each array holds the date and value.
The original json data is held in a variable $results:
foreach ($results as $result)
{
//
}
How do I achieve this?
Something like
function process_results($results) {
$out = [];
foreach ($results as $result) {
$name = $result['name'];
if ( ! $out[$name]) {
$out[$result['name']] = array( 'name' => $name, 'data' => array());
}
array_push($out[$name]['data'], array($result['date'], $result['value']));
}
return array_values($out);
}
This also seems to work
function process_results($results) {
return array_values(array_reduce($results, function($acc, $result) {
$name = $result['name'];
if ( ! $acc[$name]) {
$acc[$result['name']] = array( 'name' => $name, 'data' => array());
}
$acc[$name]['data'][] = array($result['date'], $result['value']);
return $acc;
}, []));
}

codeigniter php Severity: Notice Message: Undefined index: user_id

array(3) {
[0]=> array(15) {
["guest_list_id"]=> string(1) "0"
["event_type_id"]=> string(1) "2"
["event_id"]=> string(1) "1"
["guest_attendance_status"]=> NULL
["user_id"]=> string(1) "9" },
When accessing $user['user_id'] , I get the error:
A PHP Error was encountered
Severity: Notice
Message: Undefined index: user_id
Code from Comment
if (!empty($user)) {
foreach ($user as $key => $value) {
$user_details = array(
'user_id' => $user['0']['user_id'],
'eventTitle' => $user['pre_wedding_event_title']
);
}
}

How to get all Magento Order status (List all magento order status)

How to get a list of all magento order status (pending, complete, processing etc.)?
It should show all values like the "status" drop down field in the order-index grid page in the magento backend.
Just use this simple line of code:
Mage::getModel('sales/order_status')->getResourceCollection()->getData();
For example:
var_dump( Mage::getModel('sales/order_status')->getResourceCollection()->getData() );
Result:
array(10) { [0]=> array(2) { ["status"]=> string(8) "canceled" ["label"]=> string(8) "Canceled" } [1]=> array(2) { ["status"]=> string(6) "closed" ["label"]=> string(6) "Closed" } [2]=> array(2) { ["status"]=> string(8) "complete" ["label"]=> string(8) "Complete" } [3]=> array(2) { ["status"]=> string(5) "fraud" ["label"]=> string(15) "Suspected Fraud" } [4]=> array(2) { ["status"]=> string(6) "holded" ["label"]=> string(7) "On Hold" } [5]=> array(2) { ["status"]=> string(14) "payment_review" ["label"]=> string(14) "Payment Review" } [6]=> array(2) { ["status"]=> string(7) "pending" ["label"]=> string(7) "Pending" } [7]=> array(2) { ["status"]=> string(15) "pending_payment" ["label"]=> string(15) "Pending Payment" } [8]=> array(2) { ["status"]=> string(14) "pending_paypal" ["label"]=> string(14) "Pending PayPal" } [9]=> array(2) { ["status"]=> string(10) "processing" ["label"]=> string(10) "Processing" } }
Get all order statuses and save the array $orderStatus[status][label] in $status associative array:
$orderStatusCollection = Mage::getModel('sales/order_status')->getResourceCollection()->getData();
$status = array();
$status = array(
'-1'=>'Please Select..'
);
foreach($orderStatusCollection as $orderStatus) {
$status[] = array (
'value' => $orderStatus['status'], 'label' => $orderStatus['label']
);
}
Here is the way to get the output for dop-down:
$statuses = Mage::getModel('sales/order_status')->getCollection()
->toOptionArray()
echo '<pre>';print_r($statuses);echo '</pre>';
//this will output:
Array
(
[0] => Array
(
[status] => canceled
[label] => Canceled
)
[1] => Array
(
[status] => cancel_ogone
[label] => Cancelled Ogone
)
[2] => Array
(
[status] => closed
[label] => Closed
)
[3] => Array
(
[status] => complete
[label] => Complete
)
.....

Resources