PHP push values to nested array - php

i have the created the following object array in php
$treeData[] = (object) array(
"name"=> "A",
"children" => [
[
"name"=> "A1",
"children"=> [
[
"name"=> "A1.1",
"children"=> [
[
"name"=> "A1.1.1",
"children"=> [
....
I'm trying to push new values inside the children of A1.1.1 based on below condition:
foreach ($treeData as $value) {
if ($value->name == 'A') {
$value->name[][] = (object) array(
"name"=> "ChildA",
"children"=> ""
);
break;
}
}
But it's giving me an error
Expected result should match as below example:
$treeData[] = (object) array(
"name"=> "A",
"children" => [
[
"name"=> "A1",
"children"=> [ [
"name"=> "A1.1",
"children"=> [ [
"name"=> "A1.1.1",
"children"=> [
[
"name"=> "ChildA",
"children"=> [ [
"name"=> "ChildA1"
] ]
],
[
"name"=> "ChildA",
"children"=> [ [
"name"=> "ChildA2"
] ]
],
]
] ]
] ]
]
]);
What I'm doing wrong here or any way to achieve this in different approach
The error I'm getting:
"Fatal error: Uncaught Error: [] operator not supported for strings "

First of all you getting the error as you do: $value->name[][]. Notice the name is a string so you ccannot use [] (array append operator) on it.
I would have take the recursive approach if I were you. Consider the following pseudo code:
function addChild($root, $addToName, $nameToAdd) {
if ($root->name == $addToName)
$root->children[] = (object) array("name"=> $nameToAdd, "children"=> []);
else
foreach($root->children as $child)
addChild($child, $addToName, $nameToAdd);
}
And now call is with: addChild($treeData, 'A', "ChildA")

Related

Issue with mysql loop

Intuit integration.
With create invoice. I am needing to get items from a loop when I create the invoice.
I also tried by creating the loop first and using $items in the invoice create but also get an error. "Format Error. Expect an element of an array or an object."
Not liking my loop. How can I accomplish this
?
$theResourceObj = Invoice::create([
"TotalAmt" => 200.00,
"Line" => [
$queryitems = 'SELECT * FROM mydatabse',
$query_items = mysqli_query($con,$queryitems),
while($row = mysqli_fetch_array($query_items)) {
[
"Description"=> "Loop Description",
"DetailType"=> "SalesItemLineDetail",
"SalesItemLineDetail"=> [
"TaxCodeRef"=> [
"value"=> "TAX"
],
"Qty"=> 1,
"UnitPrice"=> 200,
"ItemRef"=> [
"name"=> "Loop Name",
"value"=> "5"
]
],
"LineNum"=> 1,
"Amount"=> 200.00,
"Id"=> "1"
],
}
],
"CustomerRef"=> [
"value"=> 1
],
"BillEmail" => [
"Address" => "email#somewhere.com"
]
]);
You can't put loops inside array literals.
Construct the array incrementally outside the call to Invoice::create().
$invoice = [
"TotalAmt" => 200.00,
"CustomerRef"=> [
"value"=> 1
],
"BillEmail" => [
"Address" => "email#somewhere.com"
]
];
$lines = [];
$queryitems = 'SELECT * FROM mydatabse';
$query_items = mysqli_query($con,$queryitems);
while($row = mysqli_fetch_array($query_items)) {
$lines[] = [
"Description"=> "Loop Description",
"DetailType"=> "SalesItemLineDetail",
"SalesItemLineDetail"=> [
"TaxCodeRef"=> [
"value"=> "TAX"
],
"Qty"=> 1,
"UnitPrice"=> 200,
"ItemRef"=> [
"name"=> "Loop Name",
"value"=> "5"
]
],
"LineNum"=> 1,
"Amount"=> 200.00,
"Id"=> "1"
];
}
$invoice['Line'] = $lines;
$theResourceObj = Invoice::create($invoice);

Illegal Argument Exception when using Suggestors in Elasticsearch in PHP

I have tried implementing completion suggestor query in php as given here. My code is :
$params = [
"index" => $myIndex,
"body" => [
"try" => [
"text" => "ram",
"completion" => [ "value" => "suggest"]
]
]
];
$response = $client->suggest($params);
I have done indexing like this:
$params = [
"index" => $myIndex,
"body" => [
"settings"=> [
"analysis"=> [
"analyzer"=> [
"start_with_analyzer"=> [
"tokenizer"=> "my_edge_ngram",
"filter"=> [
"lowercase"
]
]
],
"tokenizer"=> [
"my_edge_ngram"=> [
"type"=> "edge_ngram",
"min_gram"=> 3,
"max_gram"=> 15
]
]
]
],
"mappings"=> [
"doc"=> [
"properties"=> [
"label"=> [
"type"=> "text",
"fields"=> [
"keyword"=> [
"type"=> "keyword"
],
"ngramed"=> [
"type"=> "text",
"analyzer"=> "start_with_analyzer"
]
]
]
]
]
]
]
];
$response = $client->indices()->create($params); // create an index
and I am getting the following error:
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "[completion] unknown field [value], parser not found"
}
],
"type": "illegal_argument_exception",
"reason": "[completion] unknown field [value], parser not found"
},
"status": 400
}
I have tried changing value to value.keyword but it is showing same error. I am using elastic search 5.3.2 . How to resolve this error?
In the query you are using field 'value' inside the completion while it is not a field like this, that is the exact error is stating.
You can try the below solution:
$params = [
"index" => $myIndex,
"body" => [
"try" => [
"text" => "ram",
"completion" => [ "label" => "suggest"]
]
]
];
$response = $client->suggest($params);
Hope this will work.

How do I extract subdocument in laravel mongodb

Hello Good Developers,
I am using jenssegers/laravel-mongodb package to query my MongoDB from Laravel.
Here's Fiddle for my query: https://mongoplayground.net/p/qzbNN8Siy-3
I have following JSON
[{
"id": "GLOBAL_EDUCATION",
"general_name": "GLOBAL_EDUCATION",
"display_name": "GLOBAL_EDUCATION",
"profile_section_id": 0,
"translated": [
{
"con_lang": "US-EN",
"country_code": "US",
"language_code": "EN",
"text": "What is the highest level of education you have completed?",
"hint": null
},
{
"con_lang": "US-ES",
"country_code": "US",
"language_code": "ES",
"text": "\u00bfCu\u00e1l es su nivel de educaci\u00f3n?",
"hint": null
}...
{
....
}
]
I am trying to run following command
db.collection.find({ 'id': "GLOBAL_EDUCATION" },{_id:0, id:1, general_name:1, translated:{ $elemMatch: {con_lang: "US-EN"} }})
Expecting result like this
[
{
"general_name": "GLOBAL_EDUCATION",
"id": "GLOBAL_EDUCATION",
"translated": [
{
"con_lang": "US-EN",
"country_code": "US",
"hint": null,
"language_code": "EN",
"text": "What is the highest level of education you have completed?"
}
]
}
]
Everything is fine while query directly in MoDB but issue arise when I am trying this in Laravel.
I've tried every possible known function from MongoDB package. but Not able to do this.
here's my Array
$findArray = [
[
'id' => "GLOBAL_EDUCATION",
],
[
'_id' => 0,
'id' => 1,
'general_name' => 1,
'translated' => [
'$elemMatch' => ['con_lang' => "US-EN"]
],
]
];
$model = GlobalQuestions::raw()->find($findArray) //OR
$data = GlobalQuestions::raw(function($collection) use ($findArray){
return $collection->find($findArray);
});
What I am doing wrong here, is this kind of Find() not possible here and I've to do this by aggregation?
Since no-one answered this, I am posting the solution if someone is having the same issue.
Doing some more R&D on the same I was able to do this using where and Project as well by Aggregation Pipelines.
----- Using Where() and Project() ------
$projectArray = [
'_id' => 0,
'id' => 1,
'general_name' => 1,
'translated' => [
'$elemMatch' => ['con_lang' => "FR-FR"]
],
];
$data = GlobalQuestions::where('id', '=', 'GLOBAL_EDUCATION')
->project($projectArray)
->get();
--- Using Aggregation and $unwind ---
$data = GlobalQuestions::raw(function($collection) {
return $collection->aggregate([
[
'$match' => [
'id' => "GLOBAL_EDUCATION"
]
],
[
'$unwind' => '$translated',
],
[
'$match' => [
'translated.con_lang' => "US-EN"
]
],
[
'$project' => [
'_id'=> 0,
'id'=> 1,
'general_name' => 1,
'translated' => 1,
]
]
]);
})->first();

Sending Json with Guzzle

I need to send Json with one of the parameters being an array . The following code works perfectly .
$html = $client->post($url,
['json'=>[ 'requestData'=>
[
'sessionID'=>'261-7306141-0539957'
]
,
'productTargets'=>
[
[ 'ProductID'=>$data[0] ],
[ 'ProductID'=>$data[1] ],
[ 'ProductID'=>$data[2] ],
[ 'ProductID'=>$data[3] ],
[ 'ProductID'=>$data[4] ],
],
] ]
);
As you can see I am manually entering data[0],data[1],data[2] in productTargets . I need to send multiple like 100's of
'ProductID' object . I tried using
json_encode( [ [ 'ProductID'=>$data[0] ],
['ProductID'=>$data[2] ],
['ProductID'=>$data[3] ],
['ProductID'=>$data[4] ], ]
)
But it's not working . How do I send the data
Perhaps an approach like this:
<?php
$data =
[
'json' =>
[
'requestData'=>
[
'sessionID'=>'261-7306141-0539957'
]
]
];
$ids = range(1, 4); // Some dummy ids.
shuffle($ids);
$product_ids = array_map(function($v) {
return ['ProductID' => $v];
}, $ids);
$data['json']['productTargets'] = $product_ids;
var_dump(json_encode($data, JSON_PRETTY_PRINT));
Example output:
string(383) "{
"json": {
"requestData": {
"sessionID": "261-7306141-0539957"
},
"productTargets": [
{
"ProductID": 4
},
{
"ProductID": 3
},
{
"ProductID": 1
},
{
"ProductID": 2
}
]
}
}"

How can I find values in an array which match criteria, without using a for loop?

I have an array like this
$a = [
[
"id" => "1",
"values" => [
"1",
"2"
]
],
[
"id" => "2",
"values" => [
"1",
"3"
]
],
[
"id" => "3",
"values" => [
"2",
"4"
]
],
[
"id" => "4",
"values" => [
"4",
"6"
]
],
];
to search and return the array that 'values' has 2
$result = [
[
"id" => "1",
"values" => [
"1",
"2"
]
],
[
"id" => "3",
"values" => [
"2",
"4"
]
],
];
Yes, I can do with for loop, and use in_array to return the result, just thinking whether there is elegant (better) way to do it?
$result = [];
foreach ($a as $datum) {
if (in_array('2', $datum['values'])) {
$result[] = $datum;
}
}
I tried array_search, but it does not support nested array
array_search('2', array_column($a, 'values'));
You can use array_filter() and in_array():
$value = '2';
$result = array_filter($a, function (array $element) use ($value) {
return array_key_exists('values', $element)
&& is_array($element['values'])
&& in_array($value, $element['values'], true);
});
var_dump($result);
For reference, see:
http://php.net/manual/en/function.array-filter.php
http://php.net/manual/en/function.in-array.php
For an example, see:
https://3v4l.org/4HnFV

Categories