I want to dynamically create a short array with a list of objects. This is for a POST request with the Guzzle client. That's why I need it in a short array.
example of a Guzzle post request:
$res = $this->client->request($methode, $request_url, [
'form_params' => [
'param' => 'value'
]
]);
Problem case:
I have got a List: Params of Objects: Param.
Param has three attributes id, name, link_id.
Let's say the List has three Object.
param(1, email, 1)
param(2, username, 1)
param(3, password, 1)
I want to dynamically create from the list an array with the short array syntax.
Example(Pseudo):
for each params as param
[
'form_params' => [
param->name => 'value'
]
]
the result of this code will be like this
[
'form_params' => [
'email' => 'value',
'username' => 'value',
'password' => 'value'
]
]
Code example:
$params = array(
"param" => array (
"id" => "1",
"name" => "username",
"link_id" => "1",
)
);
$value = '';
$shortarray = '';
foreach($params as $key => $param){
$shortarray .= $param->name . '=>' . $value . ',';
}
$postParams = ['form_params' => [ . $shortarray . ]];
I really could use some help. Thank you in advance.
If you want to just show short array syntax than this solution may helps you to resolve you problem.
https://stackoverflow.com/a/35207172/4781882
I am not quite sure why you require it be a "short array", but here's a solution...
I assume this is a web form, yes?
So let's assume you name your forms in a way that is usable, like:
<form method="POST" action="yourform.html">
Line 1 <input name="email1"> | <input name="user1"> | <input name="password1">
<br/>-------<br/>
Line 2 <input name="email2"> | <input name="user2"> | <input name="password2">
<br/>-------<br/>
Line 3 <input name="email3"> | <input name="user3"> | <input name="password3">
</form>
Then...
for($i = 1; $i <= 3; $i++ {
$postparms[] = ['email' => $_POST['email'.$i], 'user' => $_POST['user'.$i], 'password' => $_POST['password'.$i] ];
}
print_r($postparms);
Related
Im not sure if the question title is correct but what I wanna do is clear in the example below
I have 3 arrays and I want to store data in one table
the table structure is like this
table name: tour_transports
id
transport_id
transport_track
transport_note
arrays coming from blade
"transport_id" => array:2 [
1 => "1"
5 => "5"
]
"transport_track" => array:3 [
1 => " from airport to the hotel"
3 => null
5 => " be ready at 4:pm"
]
"transport_note" => array:3 [
1 => "from hotel to the beach"
3 => null
5 => " bring ur swiming suite"
]
so as you see the ids are 1 and 5 so I wanna store two rows here
id = 1,transport_id = 1 , transport_track = from airport to the hotel , transport_note = be ready at 4:pm
id = 2,transport_id = 5, transport_track = from hotel to the beach , transport_note = bring ur swiming suite
I tried to do this but can't get it correct
if(!empty($request->transport_id))
{
foreach ($request->transport_id as $key => $transport_id) {
foreach ($request->transport_track as $key => $track) {
foreach ($request->transport_note as $key => $transport_note) {
TourTransport::create([
'transport_id' =>$transport_id,
'transport_track' =>$track[$transport_id],
'transport_note' =>$transport_note[$transport_id]
]);
}
}
}
}
You can use this code to achieve your results:
$data = $request->only('transport_id', 'transport_track', 'transport_note');
foreach ($data['transport_id'] as $key => $transportId) {
TourTransport::create([
'transport_id' => $transportId,
'transport_track' => $data['transport_track'][$key],
'transport_note' => $data['transport_note'][$key],
]);
}
Now $results contains the required data. However the better solution might be to configure your html form to send related data in single array entry, Like:
<input type="text" name="transports[0][transport_id]">
<input type="text" name="transports[0][transport_track]">
<input type="text" name="transports[0][transport_note]">
<input type="text" name="transports[1][transport_id]">
<input type="text" name="transports[1][transport_track]">
<input type="text" name="transports[1][transport_note]">
Which you can also use Javascript/php loops to generate the form inputs. Then you will receive form data in server side in well formed structure like:
"transports" => array:2 [
[
'transport_id' => 1,
'transport_track' => 'from airport to the hotel',
'transport_note' => 'be ready at 4:pm',
],
[
'transport_id' => 5,
'transport_track' => 'from hotel to the beach',
'transport_note' => ' bring ur swiming suite',
],
]
I have been using Elasticsearch 7.6 and PHP client API for all the operations.
I have created elasticsearch index settings and mappings as follows
$params = [
'index' => 'elasticindex',
'body' => [
'settings' => [
"number_of_shards" => 1,
"number_of_replicas" => 0,
"index.queries.cache.enabled" => false,
"index.soft_deletes.enabled" => false,
"index.requests.cache.enable" => false,
"index.refresh_interval" => -1
],
'mappings' => [
'_source' => [
"enabled" => false
],
'properties' => [
"text" => [
"type" => "text",
"index_options" => "docs"
]
]
]
]
];
I was able to index document using the following code
$params = array();
$params['index'] = 'elasticindex';
for($i = 1; $i <=2; $i++) {
$params['id'] = $i;
$params['body']['text'] = 'apple';
$responses = $client->index($params);
}
But when I use the following search query
$params = [
'index' => 'elasticindex',
'body' => [
'query' => [
'match' => [
"text" => "apple"
]
]
]
];
$results = $client->search($params);
I am getting empty results as follows
Array
(
[took] => 3
[timed_out] =>
[_shards] => Array
(
[total] => 1
[successful] => 1
[skipped] => 0
[failed] => 0
)
[hits] => Array
(
[total] => Array
(
[value] => 0
[relation] => eq
)
[max_score] =>
[hits] => Array
(
)
)
)
Without creating a static index template, if I try to index, elasticsearch dynamic mapping works well and I am getting the results.
The goal is that I want the elasticsearch to index only document id in its inverted index and not position or offset and I want to retrieve only matching document ids as results. Help is much appreciated. Thanks in advance!
Since the document is being returned by the get handler and not the query handler, your index is not being refreshed properly after indexing the document.
As you noted yourself, in your configuration you set:
"index.refresh_interval" => -1
.. which means that the index is not being refreshed automagically. There's seldom a need to change the refresh interval, except in very high throughput situations or where a particular behavior is wanted.
Try to index doc something like this.
$client = Elasticsearch\ClientBuilder::create()
->setHosts($hosts)
->build();
$params = [
'index' => 'elasticindex',
'type' => 'documents',
'id' => '1',
'body' => ['text' => 'apple']
];
$response = $client->index($params);
print_r($response);
Note: _id you can define dynamically if you want, else id will automatically set by elastic.
And try to get doc via a search query.
{
"query": {
"bool": {
"must": {
"term": {
"text": "apple"
}
}
}
}
}
If you want full-text search on this key, set this key property as
"properties": {
"name": {
"type": "text"
}
}
I got this:
$arr = json_decode($arr, TRUE);
while($row){
// $arr[] = ['id' => '8', 'name' => 'mickey'];
$test = $row->TCI_LIBELLE;
$arr[] = ['id' => $row->TCI_ID, 'name' => $row->TCI_LIBELLE];
$i +=1;
$row = $reqCentreInteret->fetch(PDO::FETCH_OBJ);
$json = json_encode($arr);
If you don't understand I'm trying to put values I get from a Select SQL query into a JSON array.
The problem is that it does't work like I want.
Indeed it works with my id because in my database it's an int value, but it does't work for the name because it is a varchar value
This is what i want to obtain :
[{"id":"8","name":"mickey"},{"id":"8","name":"mickey"}]
And here 'mickey' will be replaced by the value of my php string that will be initialized by my sql query
I already tried to solve my problem using
'name' => '" .$row->TCI_LIBELLE."'
But it does't work
How can I pass string value (or other type) to my JSON array?
I'm using PHP and JSON to send value from MySQL to an Android app.
arr[] = adds a new row to the array, i.e. a new top-level element.
You probably want to add your data to the existing element
Let's say your arr initially is something like
[ 'property1' => 'value1',
'property2' => 'value2'
...]
when you're doing
arr[] = ['id'=> 8,'name' => 'mickey']
your array will now contain 2 top level elements and look like
[[ 'property1' => 'value1',
'property2' => 'value2'
...
],
[ 'id' => 8,
'name' => 'mickey'
]
]
you may want to do this instead
arr['id'] = $row->TCI_ID;
arr['name'] = $row->TCI_LIBELLE;
then your arr will look like this:
[ 'property1' => 'value1',
'property2' => 'value2'
'id' => 8
'name' => 'mickey'
...
]
Finally this is what is had to do
$stmt = $db->query("SELECT TCI_ID AS id, TCI_LIBELLE AS nom FROM
OSO_DEV.T_CENTRE_INTERET");
echo json_encode($stmt->fetchAll(PDO:: FETCH_ASSOC),JSON_UNESCAPED_UNICODE);
I have a probleme with a array.
In my array that has 15,000 rows, I have columns with associated names and values (sku).
I need to show all the names and make a separate on it if the sku is equal or not to the sku that is present on my product page
Exemple : array = [ 'code' => 'name1' ,
'sku' => '123456',
'code' => 'name1',
'sku' => '456789',
'code' => 'name2',
'sku' => '4565999']
etc ..........
if sku equals sku or not in my page product, i want to show the code with distinct on this .
First you need an array of arrays structure like this:
$arr = [
[ 'code' => 'name1', 'sku' => '123456' ],
[ 'code' => 'name2', 'sku' => '456789' ],
[ 'code' => 'name3', 'sku' => '4565999' ],
.
.
.
Then you can filter your array like this:
$existing_items_on_array = array_filter($arr,
function($item) use ($existing_items_on_page){
return array_search($item["sku"], $existing_items_on_page) !== false;
});
Or better (you still need to structure an array like on first solution):
I assume your SKU's are unique. Why not make them array keys?
$item_codes = [];
foreach($arr as $item){
$item_codes[$item["sku"]] = $item["code"];
}
then you would be accessing any element's code like this:
echo $item_codes[$product["sku"]]
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'];