I have this code and its working:
...
],
(
($post['categories']['show'] ?
[
'name' => "categories",
'data' => ['categories' => self::getCategories($post)]
] : ''
),
[
...
However if its false its returning "" on the output but if its false it should not return nothing it should not show nothing. Do you know how to achieve that? With : null, it shows null, instead oof "",.
I also tried like this but don't works:
$result = [
'components' => [
[
...
],
if($post['categories']['show'])
{
[
'name' => "categories",
'data' => ['categories' => self::getCategories($post)]
];
}
....
];
return $result;
}
The whole code is really big. But it follows that structure array then ",".
Don't use an empty string for the else conditional, use null, then use array_filter, it will clean all null values of the array for you:
$result = [
$condition ? 'bar' : null,
'foobaz',
...
];
// return value will be: ["foobaz"]
return array_filter($result);
Related
I have an array with a structure like:
$arr = [
'data1' => [ /* some data */],
'data2' => [
'sub-data1' => [
[
'id' => 1
'status' => 'active'
],
[
'id' => 2
'status' => 'not-active'
]
],
'sub-data2' => [
[
'id' => 3
'status' => 'active'
],
[
'id' => 4
'status' => 'active'
]
]
]
]
Is there a simple way in which I can count how many sub-dataxxx have any item with a status is active?
I have managed to do this with nested foreach loops, but I'm wondering if there is a more simple method?
The above example should show the number of active entries as 2, as there are 2 sub-data elements with active statuses. This ignores any non-active statuses.
Edit: To clarify my expected result
I am not wanting to count the number of status = active occurrences. I'm wanting to count the number of sub-dataxxx elements that contain an element with status = active.
So in this instance, both of sub-data1 and sub-data2 contain sub-elements that contain status = active, therefore my count should be 2.
you can do it quite easily with a function like this
function countActiveSubData(array $data): int
{
return array_reduce($data, function ($res, $sub) {
foreach ($sub as $d) {
if ('active' === $d['status']) {
return $res + 1;
}
}
return $res;
}, 0);
}
you can call it on a single data or if you want to get the result for entire $arr you can call it like this
$result = array_map('countActiveSubData', $arr);
// the result will be [
'data1' => 0,
'data2'=> 2
....
]
I have below array, I need to append a new array inside $newData['_embedded']['settings']['web/vacation/filters']['data'], How can I access and append inside it ?
$newData = [
"id" => "47964173",
"email" => "abced#gmail.com",
"firstName" => "Muhammad",
"lastName" => "Taqi",
"type" => "employee",
"_embedded" => [
"settings" => [
[
"alias" => "web/essentials",
"data" => [],
"dateUpdated" => "2017-08-16T08:54:11Z"
],
[
"alias" => "web/personalization",
"data" => [],
"dateUpdated" => "2016-07-14T10:31:46Z"
],
[
"alias" => "wizard/login",
"data" => [],
"dateUpdated" => "2016-09-26T07:56:43Z"
],
[
"alias" => "web/vacation/filters",
"data" => [
"test" => [
"type" => "teams",
"value" => [
0 => "09b285ec-7687-fc95-2630-82d321764ea7",
1 => "0bf117b4-668b-a9da-72d4-66407be64a56",
2 => "16f30bfb-060b-360f-168e-1ddff04ef5cd"
],
],
"multiple teams" => [
"type" => "teams",
"value" => [
0 => "359c0f53-c9c3-3f88-87e3-aa9ec2748313"
]
]
],
"dateUpdated" => "2017-07-03T09:10:36Z"
],
[
"alias" => "web/vacation/state",
"data" => [],
"dateUpdated" => "2016-12-08T06:58:57Z"
]
]
]
];
$newData['_embedded']['settings']['web/vacation/filters']['data'] = $newArray;
Any Hint to quickly append it, I don't want to loop-in and check for keys inside loops.
The settings subarray is "indexed". You first need to search the alias column of the subarray for web/vacation/filters to find the correct index. Using a foreach loop without a break will mean your code will continue to iterate even after the index is found (bad coding practice).
There is a cleaner way that avoids a loop & condition & break, use array_search(array_column()). It will seek your associative element, return the index, and immediately stop seeking.
You can use the + operator to add the new data to the subarray. This avoids calling a function like array_merge().
Code: (Demo)
if(($index=array_search('web/vacation/filters',array_column($newData['_embedded']['settings'],'alias')))!==false){
$newData['_embedded']['settings'][$index]['data']+=$newArray;
}
var_export($newData);
Perhaps a more considered process would be to force the insert of the new data when the search returns no match, rather than just flagging the process as unsuccessful. You may have to tweak the date generation for your specific timezone or whatever... (Demo Link)
$newArray=["test2"=>[
"type" =>"teams2",
"value" => [
0 => "09b285ec-7687-fc95-2630-82d321764ea7",
1 => "0bf117b4-668b-a9da-72d4-66407be64a56",
2 => "16f30bfb-060b-360f-168e-1ddff04ef5cd"
],
]
];
if(($index=array_search('web/vacation/filters',array_column($newData['_embedded']['settings'],'alias')))!==false){
//echo $index;
$newData['_embedded']['settings'][$index]['data']+=$newArray;
}else{
//echo "couldn't find index, inserting new subarray";
$dt = new DateTime();
$dt->setTimeZone(new DateTimeZone('UTC')); // or whatever you are using
$stamp=$dt->format('Y-m-d\TH-i-s\Z');
$newData['_embedded']['settings'][]=[
"alias" => "web/vacation/filters",
"data" => $newArray,
"dateUpdated" => $stamp
];
}
You need to find the key that corresponds to web/vacation/filters. For Example you could use this.
foreach ($newData['_embedded']['settings'] as $key => $value) {
if ($value["alias"]==='web/vacation/filters') {
$indexOfWVF = $key;
}
}
$newData['_embedded']['settings'][$indexOfWVF]['data'][] = $newArray;
From the comments. Then you want to merge the arrays. Not append them.
$newData['_embedded']['settings'][$indexOfWVF]['data'] = array_merge($newData['_embedded']['settings'][$indexOfWVF]['data'],$newArray);
Or (if it's always Filter1):
$newData['_embedded']['settings'][$indexOfWVF]['data']['Filter1'] = $newArray['Filter1'];
I'm working with mongodb in laravel using jenssegers driver and i have 3 documents likes this in my db
{
"_id" : ObjectId("594dd540bb7de924c0005583"),
"cliente" : "Luis",
"tipo" : "Luis",
"paquete" : "Luis",
"fecha" : null,
"fechaE" : null,
"content" : "fotos",
"precio" : NumberInt(200),
"estatus" : NumberInt(2),
"Abonos" : [
{
"Monto" : NumberInt(200),
"Fecha" : null
},
{
"Monto" : NumberInt(2000),
"Fecha" : null
},
{
"Monto" : NumberInt(2000),
"Fecha" : null
}
],
"updated_at" : ISODate("2017-06-24T02:58:08.000+0000"),
"created_at" : ISODate("2017-06-24T02:58:08.000+0000")}
Im using this Raw query to get que $sum of all "monto" for each document(3 documents).
public function updatearray(Request $request, $id){
$works = new work;
$result = Work::raw(function($collection)
{
return $collection->aggregate(array(
array('$unwind' => '$Abonos'),
array('$group' =>
array( "_id" => '$_id',"Monto" => array('$sum' => '$Abonos.Monto'))),
));
});}
I only want to display the results for my current document, is there a way i can match with the current $id?
-- Edit
Im getting id from a get method
public function abono($id){
$work = work::find($id);
return view('workabono', compact('work'));
}
and these are the routes that i use
Route::get('works/{work}/abono', [
'as' => 'works.abono', 'uses' => 'WorkController#abono']);
Route::put('works/{work}/', [
'as' => 'works.updateAbono', 'uses' => 'WorkController#updatearray']);
You don't even need the $unwind here. Simply $match and $project:
public function updatearray(Request $request, $id){
$works = new work;
$result = Work::raw(function($collection) use($id)
{
return $collection->aggregate(array(
array('$match' => array( '_id' => $id) ),
array('$project' =>
array( "Monto" => array('$sum' => '$Abonos.Monto') )
)
));
});}
The $sum can directly add the elements from the array.
If $id is a string you can cast to ObjectId explicitly,
$id = new \MongoDB\BSON\ObjectID($id);
My code look like this:
$database->update($campaign_table, $data_nga_posti , array("AND" => ["codice_pod" => $data_nga_posti['codice_pod'],("codice_pdr" =>NULL) ]));
So this is when my query execute:
UPDATE `field` SET `columnname` = 'data',`anothercm` = 'data',WHERE `codice_pod` = 'IT001E35563561' AND `codice_pdr` IS NULL
I want to my query look like this.
UPDATE `field` SET `columnname` = 'data',`anothercm` = 'data',WHERE `codice_pod` = 'IT001E35563561' AND (`codice_pdr` IS NULL OR `codice_pdr` ="")
but I dont know how to put OR(operator ) inside this code.
I have never used this before, and have nothing to test with but the closted example posted in the documentation is:
$database->has("account", [
"AND" => [
"OR" => [
"user_name" => "foo",
"email" => "foo#bar.com"
],
"password" => "12345"
]
]);
So I think this would work for you:
$database->update($campaign_table, $data_nga_posti, [
"AND" => [
OR => [
"codice_pdr" =>NULL,
"codice_pdr" => ""
],
"codice_pod" => $data_nga_posti['codice_pod']
]
]);
try this:
array("AND" => ["codice_pod" => $data_nga_posti['codice_pod'],"OR" => ["codice_pdr" =>NULL,`codice_pdr` ="" ] ])
I have the following type of occurrence in my Mongo documents.
"tags" : [ [ "narnia" ], [ "aslan" ], [ "winter" ], [ "heaven" ] ]
I need to know how to find this document by matching all of any number of the tags. I.e. Narnia AND Aslan (but not Narnia OR Aslan).
The query needs to be made with in PHP.
So far I only have it working for a single tag. I.e.
$filter['tags'] = array('$in' => array(array('Narnia')));
As Hussain mentioned in comments - you might want to revise that document structure as seems like you're storing unnecessary arrays.
Otherwise, what you're trying to do could be done with an $and statement (example without the nested arrays):
PRIMARY> db.wardrobe.find({ $and: [ { tags: "narnia" }, { tags: "tugboat" } ] })
//returns nothing
PRIMARY> db.wardrobe.find({ $and: [ { tags: "narnia" }, { tags: "winter" } ] })
//returns { "_id" : ObjectId("521067a48202463b88c2a0c9"), "tags" : [ "narnia", "aslan", "winter", "heaven" ] }
In PHP:
//With your nested arrays:
$filter = array(
'$and' => array(
array('tags' => array('narnia') ),
array('tags' => array('aslan') )
)
);
//With a simple array:
$filter = array(
'$and' => array(
array('tags' => 'narnia'),
array('tags' => 'aslan')
)
);
$mongoClient->selectCollection('cwlewis', 'wardrobe')->find( $filter );