How do I correct this one line PHP syntax? - php

newbie here. I have the following PHP-code for a script with Betfair-API.
if ($event->marketName == "Match Odds") {
// print_r($event);
$params = [
"marketIds" => [$event->marketId],
'priceProjection' => ['priceData' => ['EX_BEST_OFFERS']]
];
}
I need to add virtual bets. API-documentation says:
You can return virtual bets in the response when using API-NG by including the virtualise":"true" in the listMarketBook request e.g.
[
{
"jsonrpc":"2.0",
"method":"SportsAPING/v1.0/listMarketBook",
"params":{
"marketIds":[
"1.114101556"
],
"priceProjection":{
"priceData":[
"EX_BEST_OFFERS"
],
"virtualise":"true"
}
},
"id":1
}
]
How can I change my code to work? I've tried a few dozen combinations, but no luck. Sorry for being newbie.
David

$params = [
"marketIds" => [$event->marketId],
'priceProjection' => ['priceData' => ['EX_BEST_OFFERS']],
'virtualise' => true,
];

Related

How to cancel update in elasticsearch painless script

While working on trying to switch out PHP code with pure elasticsearch-painless, I noticed that the document doesn't return "noop" even if the document is identical before and after update.
I'm not sure if there is any consequences of having a version update for every time the code is executed? How does it scale?
I'm simply trying to update the views of a post during visit if the identity was not found in views_log, and was wondering either if there is a way to fix the "noop" return, or somehow have it cancel the update?
The code I have right now looks like this:
$script = 'if (!ctx._source.views_log.contains(params.identity)) {
ctx._source.views_log.add(params.identity);
ctx._source.views += 1;
}';
$params = [
'index' => 'post',
'id' => 4861,
'body' => [
'script' => [
'source' => $script,
'lang' => "painless",
'params' => [
'identity' => $identifier
]
]
]
];
$response = $client->update($params);
Following elasticsearch's documentation:
ctx['op']:
Use the default of index to update a document. Set to none to specify no operation or delete to delete the current document from the index.
I tried setting ctx.op to none if the condition is not met, but that didn't seem to work.
During writing of this question I figured it out, and might as well share with others.
none is an accepted keyword for ctx.op, it accepts a string. Change none to "none".
So the full script should look like this:
$script = 'if (!ctx._source.views_log.contains(params.identity)) {
ctx._source.views_log.add(params.identity);
ctx._source.views += 1;
} else {
ctx.op = "none";
}';
$params = [
'index' => 'post',
'id' => 4861,
'body' => [
'script' => [
'source' => $script,
'lang' => "painless",
'params' => [
'identity' => $identifier
]
]
]
];
$response = $client->update($params);
This will give the desired "result": "noop"

PHP: array_map to return specific array of objects

I have a codepen here which shows a large array of objects. From which I would like to extract a specific property and display as shown in the console log, but in PHP.
Unfortunately for me, I'm quite new to PHP and can't seem to figure it out:
My attempt so far:
$suppliersNotInDB = array_map(function ($order) {
if (isset($order->items) && is_array($order->items)) {
return array_map(function ($item) {
return [...$item];
}, $order->items);
}
}, $ordersData);
Which, I understand isn't even remotely close, but I've been at it for hours now. Any help would be appreciated.
The long and short is that I want to perform this filtering and sorting in the backend(Laravel), not the frontend, where there is already too much going on.
Since you are using Laravel, start using Collections.
If I understood correctly what you are trying to do in your Javascript example, this can be done in a one-liner:
$suppliersNotInDB = collect($ordersData)
->pluck('items')
->flatten()
->pluck('supplier')
->unique()
->map(
fn($supplier) => ['name' => $supplier, 'lowercased' => strtolower($supplier)]
)
->values();
This can probably be further refined, just quickly jotted it down to reproduce your result.
The output of this would then be:
=> Illuminate\Support\Collection {#4999
all: [
[
"name" => "Walmart",
"lowercased" => "walmart",
],
[
"name" => "Bestbuy",
"lowercased" => "bestbuy",
],
[
"name" => "TCI",
"lowercased" => "tci",
],
[
"name" => "lkj",
"lowercased" => "lkj",
],
[
"name" => "Thousand Needles",
"lowercased" => "thousand needles",
],
],
}

Get specific value from json response not working

enter image description here
I have the following json response as in the image. I would want to access specific value, like: "ROUMANIE ROVA AROMANIA" but I can't seem to get to it. I tried the following:
$response = json_decode($r->getBody(),true);
foreach($response['ParsedResults'] as $key)
{
foreach($key['TextOverlay']['Lines'] as $bla)
{
echo $bla['LineText'];
echo $bla[0]['LineText'];
}
}
If I only echo one depth, it's working. I searched for a solution but none did the trick. Thanks.
0 is the current index of the first item, $bla contains already the data you're looking for, so doing this directly should work:
echo $bla['LineText'];
Here is how the full code should look like:
$response = [
'ParsedResults' => [
[
'TextOverlay' => [
'Lines' => [
[
'LineText' => 'ROUMANIE ROVA AROMANIA',
'Words' => [
[
'WordText' => 'ROUMANIE',
'OtherData' => 'whatever'
],
[
'WordText' => 'ROVA',
'OtherData' => 'whatever'
],
[
'WordText' => 'AROMANIA',
'OtherData' => 'whatever'
],
]
]
]
]
]
]
];
foreach($response['ParsedResults'] as $key)
{
foreach($key['TextOverlay']['Lines'] as $bla)
{
echo $bla['LineText'];
}
}
Tested here: http://sandbox.onlinephpfunctions.com/code/0577e854eed73dfb33193c391acc37dd81baf982

DBIx::Class (Perl ORM) equivalent in PHP

We started our web-based app back in 2012 when Perl was still popular. Now we want to reimplement it in PHP, preferably Laravel. However, I miss the power of DBIx::Class in their default ORM, Eloquent, and the alternative, Doctrine, from reading the docs seems more complicated, but doesn't solve the issue either. What I use DBIx::Class for:
Regenerate model classes from reading the DB structure, preserving any code that has been added to them (should have).
Generate complex queries (incl. nested joins, subqueries) from pure language constructs, no SQL needed (must have).
Code sample:
rows => $rows,
page => $page,
'select' => [
'entity_id',
{ group_concat => [ { distinct => 'pictures.id' } ], -as => 'photos' },
{ '' => [ 'entity.name' ], -as => 'entity_name' },
{ '' => [ 'municipality.name' ], -as => 'municipality_name' },
{ '' => [ 'me.birth_date' ], -as => 'bd' },
{ concat => [ { date_format => [ 'me.birth_date', \$c->config->{dateFormat} ] }, \"' ('", { timestampdiff => [ \'YEAR', 'me.birth_date', \'CURDATE()' ] }, \"')'" ], -as
{ date_format => [ 'me.birth_date', \$c->config->{dateFormat} ], -as => 'bd1' },
{ timestampdiff => [ \'YEAR', 'me.birth_date', \'CURDATE()' ], -as => 'bd2' },
{ '' => [ 'entity_state_type.name' ], -as => 'entity_state_name' },
{ '' => [ 'data_list_item.name' ], -as => 'entity_state_reason_name' },
{ '' => [ 'entity_state.note_text' ], -as => 'entity_state_note' },
{ '' => [ { if => [ 'entity.archived', \"'Yes'", \"''" ] } ], -as => 'entity_archived' },
],
join => {
entity => [ 'municipality', 'pictures', { 'entity_state' => [ 'entity_state_type', 'data_list_item' ] } ],
},
group_by => [ 'entity.id' ],
Subclass the result (row) and resultset classes to add user role-based limiting conditions transparently to the application code (must have, or equivalent).
The call and the resulting query:
$c->model('DB::Person')->all
SELECT * FROM person WHERE owner = <user_id>
...if the user role security settings indicate user should only access his own persons.
The security settings are read from DB on request start and specify which security conditions (separate classes) should apply to which table.
This moves all security away from application code, where mistakes are made most often.
Which PHP library would allow us to implement this?

How to write MongoDB query in core PHP?

I have created query in mongoDB. In MongoChef this query produces more than 10 thousand records in less than 2 seconds. Now I want to execute this query in PHP.
So i don't know how to write query in php as I read various documents on internet but confused how to implement it.
db.PMS.aggregate(
[
{$project:
{EventTS:1,MainsPower:1,PanelID:1}
},
{$unwind:
{path:"$MainsPower",includeArrayIndex:"arrayIndex",preserveNullAndEmptyArrays:true}
},
{ $match: { "MainsPower":{$ne:null}}},
{ $match: { "EventTS":{$gt:new Date("2016-01-01")}}},
{$project:
{MainsPower:1,
PanelID:1,
timestamp:{"$add":
[{'$subtract' : ["$EventTS",new Date("1970-01-01")]},
{"$multiply":[60000,"$arrayIndex"]}
]}
}
}
]
);
You can use some resources available on the php official documentation. A mapping of sql queries in php to mongoDB queries in php can be found here.
Also I have a demo login and registration script at my github. You can view those in this repo.
If you use MongoDB PHP Library you should be able to do something similar to this:
$mongo = new MongoClient();
$database = $mongo->examples;
$collection = $database->PMS;
$pipeline = [
[
'$project' => [
'EventTS' => 1,
'MainsPower' => 1,
'PanelID' => 1,
]
],
[
'$unwind' => [
'path' => '$MainsPower',
'includeArrayIndex' => 'arrayIndex',
'preserveNullAndEmptyArrays' => true
]
],
...
];
$cursor = $collection->aggregate($pipeline);

Categories