how to format dynamically-generated nested array in PHP - php

I'm trying to dynamically generate a nested array by pulling polygon data from a database using the Pods Framework, however I'm struggling to get the formatting / syntax right (I'm not an expert when it comes to PHP).
This is my code, where "polygon_latlon" is the field containing pairs of latitude and longitude points within double quotes separated by commas which make up the (irregular) polygons:
$lines = array();
//set find parameters
$params = array(
'limit' => -1
);
//get pods object
$maps = pods( 'maps_osexplorer', $params );
//loop through records
if ( $maps->total() > 0 ) {
while ( $maps->fetch() ) {
$polygon1 = $maps->field('polygon_latlon');
$lines[] = "array($polygon1)";
}
}
$polygons1 = implode(',', $lines);
Using print_r($lines) outputs in this format:
Array (
[0] => array(“54.8209937901589 -5.1847118669456265″,”54.82875805834827 -4.873857026861909″,”55.03518041767634 -4.888625345496792″,”55.02735680301253 -5.201071164745328″,”54.8209937901589 -5.1847118669456265”)
[1] => array(“54.73307781328839 -5.107888813651375″,”54.73542913841878 -5.014843407073816″,”54.62773859547211 -5.006866177191955″,”54.63292697997008 -4.790281966946296″,”54.839371033206184 -4.804517368244679″,”54.831783194724316 -5.115474120227528″,”54.73307781328839 -5.107888813651375”)
[2] => array(“54.66161594261056 -4.714709589503054″,”54.66230647443063 -4.683739691903676″,”54.68026002182563 -4.684924716676078″,”54.679569033955396 -4.715908247171228″,”54.66161594261056 -4.714709589503054”)
[3] => array(“54.79285752469713 -4.871307801664465″,”54.799816987439904 -4.560586644307456″,”55.06913330516994 -4.577766586876797″,”55.06210435522974 -4.890565603716853″,”54.79285752469713 -4.871307801664465”)
[4] => array(“54.76588200465172 -4.675046760686505″,”54.767570233715865 -4.597418172482791″,”54.66433060233055 -4.590822213183797″,”54.66967882431423 -4.327495656368091″,”54.93904807902748 -4.34303745757995″,”54.93194793898191 -4.686064981190482″,”54.76588200465172 -4.675046760686505”)
etc
etc
);
Using print_r($polygons1) outputs in this format:
array(“54.8209937901589 -5.1847118669456265″,”54.82875805834827 -4.873857026861909″,”55.03518041767634 -4.888625345496792″,”55.02735680301253 -5.201071164745328″,”54.8209937901589 -5.1847118669456265”),
array(“54.73307781328839 -5.107888813651375″,”54.73542913841878 -5.014843407073816″,”54.62773859547211 -5.006866177191955″,”54.63292697997008 -4.790281966946296″,”54.839371033206184 -4.804517368244679″,”54.831783194724316 -5.115474120227528″,”54.73307781328839 -5.107888813651375”),
array(“54.66161594261056 -4.714709589503054″,”54.66230647443063 -4.683739691903676″,”54.68026002182563 -4.684924716676078″,”54.679569033955396 -4.715908247171228″,”54.66161594261056 -4.714709589503054”),
array(“54.79285752469713 -4.871307801664465″,”54.799816987439904 -4.560586644307456″,”55.06913330516994 -4.577766586876797″,”55.06210435522974 -4.890565603716853″,”54.79285752469713 -4.871307801664465”),
array(“54.76588200465172 -4.675046760686505″,”54.767570233715865 -4.597418172482791″,”54.66433060233055 -4.590822213183797″,”54.66967882431423 -4.327495656368091″,”54.93904807902748 -4.34303745757995″,”54.93194793898191 -4.686064981190482″,”54.76588200465172 -4.675046760686505”),
etc
etc
What I need it to output, but I can't quite find the right code / syntax for, is:
array(
array(“54.8209937901589 -5.1847118669456265″,”54.82875805834827 -4.873857026861909″,”55.03518041767634 -4.888625345496792″,”55.02735680301253 -5.201071164745328″,”54.8209937901589 -5.1847118669456265”),
array(“54.73307781328839 -5.107888813651375″,”54.73542913841878 -5.014843407073816″,”54.62773859547211 -5.006866177191955″,”54.63292697997008 -4.790281966946296″,”54.839371033206184 -4.804517368244679″,”54.831783194724316 -5.115474120227528″,”54.73307781328839 -5.107888813651375”),
array(“54.66161594261056 -4.714709589503054″,”54.66230647443063 -4.683739691903676″,”54.68026002182563 -4.684924716676078″,”54.679569033955396 -4.715908247171228″,”54.66161594261056 -4.714709589503054”),
array(“54.79285752469713 -4.871307801664465″,”54.799816987439904 -4.560586644307456″,”55.06913330516994 -4.577766586876797″,”55.06210435522974 -4.890565603716853″,”54.79285752469713 -4.871307801664465”),
array(“54.76588200465172 -4.675046760686505″,”54.767570233715865 -4.597418172482791″,”54.66433060233055 -4.590822213183797″,”54.66967882431423 -4.327495656368091″,”54.93904807902748 -4.34303745757995″,”54.93194793898191 -4.686064981190482″,”54.76588200465172 -4.675046760686505”),
etc
etc
);
i.e. I need the output from print_r($polygons1) nested within another array. How would I achieve this?
Ultimately I don't want to print the nested array but store it as a variable for use in another section of code.

Sorry I am little late but you can do it with the following piece of code,
$var = array($polygons1)

Related

query laravel not working if pass variable in Where NOT IN

I'm trying to filter items from a database table
what I do is get the ids that I want to exclude and then through -> whereNotIn in laravel, I pass the ids
$idcontracts=array();
$idbike=array();
$biciCorretta = array();
$findcontract=Contract::whereRaw('? between data_inizio and data_fine', [$datainizio])->whereRaw('? between data_inizio and data_fine', [$datafine])->get();
foreach ($findcontract as $key) {
if (!in_array($key->id,$idcontracts)) {
array_push($idcontracts,$key->id);
}
}
foreach ($idcontracts as $idcontract) {
$bike_contracts=DB::table('bike_contract')->where('contract_id',$idcontract)->get();
foreach ($bike_contracts as $bike_contract) {
if (!in_array($bike_contract->bike_id,$idbike)) {
array_push($idbike,$bike_contract->bike_id);
}
}
}
$notid=implode("', '",$idbike);
up to this point I have no problem.
the result of "implode" gives me the ids I want to remove
this is the result of $idbike and $notid:
this is the query I write to exclude the ids found:
$bikes = Bike::with('category')->whereNotIn('id', [$notid])->orderBy('category_id')->get();
the problem is that it doesn't exclude me the ids passed with $notid
but if I manually pass the ids, it removes them instead:
$bikes = Bike::with('category')->whereNotIn('id', [40,41,34,36,39])->orderBy('category_id')->get();
am I doing something wrong?
You shouldn't implode $notid, that makes it a string and Laravels whereNotIn() already does that for you.
->whereNotIn('id', $idbike)
And remove the $notid parameter, as it is not needed.
implode will return in string, and because of that it will not work correctly, you should pass it as array instead.
If you print data
$idbike =[40,41,34,36,39];
print_r($idbike);
Output will be Array
Array
(
[0] => 40
[1] => 41
[2] => 34
[3] => 36
[4] => 39
)
and if you print below code
$notid=[implode(",",$idbike)];
print_r($notid);
The output will be
Array
(
[0] => 40,41,34,36,39
)
So your query become
->whereNotIn('id', ["40,41,34,36,39"])
so laravel searching for id of "40,41,34,36,39". so its not returning result
So you can pass array directly to wherenotin
->whereNotIn('id', $idbike)
Laravel, whereNotIn method removes elements from the collection that have a specified item value that is contained within the given array. That means you have to pass an array
So, idbike is the array you mentioned
$bikes = Bike::with('category')->whereNotIn('id', idbike)->orderBy('category_id')->get();

Break Up Array and output to table?

I run a gaming server and it keeps some information in a database.
I run a MySQL query that pulls information like cargo_items (below).
How can I format this data properly in PHP? I'd like for it to be in a table. Is that possible? My knowledge of handing arrays like this is limited do to the complex nature. This is how the data is returned from the database.
Array
(
[0] => Array
(
[0] => Array
(
[id] => 2237
[cargo_weapons] =>
[
["MMG_02_black_F","","","",[],""],
["arifle_SDAR_F","","","",[],""],
["arifle_SDAR_F","","","",[],""],
["arifle_SPAR_03_khk_F","","","",[],""],
["LMG_Zafir _F","","","",[],""],
["MMG_02_black_F","","","",[],""],
["MMG_02_black_F","","","",[],""]
]
)
)
)
The output should be a table:
Weapons
-------
MMG_02_black_F
arifle_SDAR_F
arifle_SDAR_F
arifle_SPAR_03_khk_F
LMG_Zafir_F
MMG_02_black_F
MMG_02_black_F
Since you have multidimensional array, you need custom recursion function, or, in your specific case, you could use something like this:
function get_items($item, $key)
{
if(!empty($item) && $key=='cargo_weapons')
//your html table cells
echo "$item<br>";
}
array_walk_recursive($array, 'get_items');
array_walk_recursive
will do the job (this function returns true or false), but you can (ab)use it to display desired HTML too.

MySQL & PHP - Looping a query AND "mapping" the results of each loop to a unique array WITHOUT "MySQL" functions

I'll note that this is a very special case, hence the question to begin with. Under normal circumstances, such a function would be simple:
I have an array named $post_id, which contains 5 values
(Each numerical)
In order to print each value in the array, I use the following loop:
.
for ($i = 0; $i < $num; $i++)
{
echo $post_id[$i] . ' ';
}
...Which prints the following: 49, 48, 47, 46, 43
3. In my database, I have a table that looks like this:
post_categories
_____________________
post_id | category
__________|__________
43 | puppies
43 | trucks
46 | sports
46 | rio
46 | dolphins
49 | fifa
4. So, using the data in the array $post_id, I'd like to loop a database query to retrieve each value in the category column from the post_categories table, and place them into uniquely named arrays based on the "post id", so that something like...
echo $post_id_49[0] . ' ', $post_id_46[1];
...Would print "fifa rio", assuming you use the above table.
An example of such a query:
//Note - This is "false" markup, you'll find out why below
for ($i = 0; $i < $num; $i++)
{
$query = "SELECT category FROM post_categories WHERE post_id = $post_id[$i]";
fakeMarkup_executeQuery($query);
}
Why is this a "special" case? For the same reason the above query is "false".
To elaborate, I'm working inside of a software package that doesn't allow for "normal" queries so to say, it uses it's own query markup so that the same code can work with multiple database types, leaving it up to the user to specify their database type which leaves the program to interpret the query according to the type of database. It does, however, allow the query to be stored in the same "form" that all queries are, like "$result = *query here*" (With the only difference being that it executes itself).
For that reason, functions such as mysql_fetch_array (Or any MySQL/MySQLi function akin to that) cannot, and will not work. The software does not provide any form of built in alternatives either, effectively leaving the user to invent their own methods to achieve the same results. I know, pretty lame.
So, this is where I'm stuck. As you'd expect, all and any information you find on the Internet assumes you can use these MySQL & MySQLi functions. What I need, is an alternative method to grab one array from the results of a looped query per loop. I simply cannot come to any conclusion that actually works.
tl;dr I need to be able to (1) loop a query, (2) get the output from each loop as it's own array with it's own name, and (3), do so without the use of functions like mysql_fetch_array. The query itself does not actually matter, so don't focus on that. I know what do with the query.
I understand this is horrifically confusing, long, and complicated. I've been trudging through this mess for days - Close to the point of "cheating" and storing the data I'm trying to get here as raw code in the database. Bad practice, but sure as heck a lot easier on my aching mind.
I salute any brave soul who attempts to unravel this mess, good luck. If this is genuinely impossible, let me know so that I can send the software devs an angry letter. All I can guess is that they never considered that a case like mine would come up. Maybe this is much more simple then I make it to be, but regardless, I personally cannot come to an logical conclusion.
Additional note: I had to rewrite this twice due to some un explained error eliminating it. For the sake of my own sanity, I'm going to take a break after posting, so I may not be able to answer any follow up questions right away. Refer to the tl;dr for the simplest explanation of my need.
Sure you can do this , here ( assuming $post_ids is an array of post_id that you stated you had in the OP ), can I then assume that I could get category in a similar array with a similar query?
I don't see why you couldn't simply do this.
$post_id = array(49, 48, 47, 46, 43);
$result = array();
foreach($post_id as $id)
{
//without knowing the data returned i cant write exact code, what is returned?
$query = "SELECT category FROM post_categories WHERE post_id = $id";
$cats = fakeMarkup_executeQuery($query);
if(!empty($cats)) {
if(!isset($result[$id])){
$result[$id] = array();
}
foreach( $cats as $cat ){
$result[$id][] => $cat;
}
}
}
Output should be.
Array
(
[49] => Array
(
[0] => fifa
)
[46] => Array
(
[0] => sports
[1] => rio
[2] => dolphins
)
[43] => Array
(
[0] => puppies
[1] => trucks
)
)
Ok, assuming you can run a function (we'll call it find select) that accepts your query / ID and returns an array (list of rows) of associative arrays of column names to values (row), try this...
$post_categories = [];
foreach ($post_id as $id) {
$rows = select("SOME QUERY WHERE post_id = $id");
/*
for example, for $id = 46
$rows = [
['category' => 'sports'],
['category' => 'rio'],
['category' => 'dolphins']
];
*/
if ($rows) { // check for empty / no records found
$post_categories[$id] = array_map(function($row) {
return $row['category'];
}, $rows);
}
}
This will result in something like the following array...
Array
(
[49] => Array
(
[0] => fifa
)
[46] => Array
(
[0] => sports
[1] => rio
[2] => dolphins
)
[43] => Array
(
[0] => puppies
[1] => trucks
)
)

Find with regular expression MongoDB + PHP

I'm trying to do a PHP find over a MongoDB collection using MongoRegex, but I'm not able to make it work. The code is quite easy:
$cursor = $this->collection->find($params)
//$params has this value:
//Array
//(
// [name] => MongoRegex Object
// (
// [regex] => .*victor.*
// [flags] => i
// )
// [login] => MongoRegex Object
// (
// [regex] => .*victor.*
// [flags] => i
// )
//)
This $params array is constructed with this function:
function toRegEx($entryVars=array()){
$regexVars = array();
foreach($entryVars as $var => $value){
$regexVal = html_entity_decode($value);
$regexVars[$var] = new MongoRegex("/.*".$regexVal.".*/i");
}
return $regexVars;
}
For some reason, this query is only returning the values which makes an exact match (i.e. the documents where login or name are exactly "victor"). What I want is that the query returns all the documents where login and/or name contains the word "victor". I'm pretty sure I'm missing something basic, but I'm not being able to find it. Any help is appreciated. Thanks!
I suppose you simply anchored the regexp to the beginning of the subject string (^), try without :
$regexVars[$var] = new MongoRegex("/".$regexVal."/i");
EDIT:
Also, if the print_r dump of the $params array above is accurate, you're probably missing a $or statement somewhere to reflect your conditions. By default, the mongodb query criteria are linked with a "and" logic, so your query will return records matching regexps on both fields only.

Using Valve/Steam API to get multiple IDs converted

So this is a VERY long explanation.
I have a Counter-Strike: Source server, with an in-game plugin for a store. This store saves its data in a MySQL Database (for this instance, named 'store'). The store keeps track of player's money in that database (on column 'credits' in table 'users'). It stores the clients based on a 'steam_id' (unique to every client)
The format of a 'steam_id' is (example): STEAM_0:0:123456789 OR STEAM_0:1:12345789.
My page that I have displays the top 1000 users from the database (sorted by credits).
My Problem: I need to convert these ugly steam_id's to actual names.
Where I am right now:
Steam API Documentation
According to the API documentation, I have to use 'community ids' when I query the API. If I want to get more than one user, I can use commas to separate community ids in the GET string.
(http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=APIKEY&steamids=76561197960435530,76561197960435531&format=json)
I have a function that converts the steam_id's to API-acceptable ID's.
function SteamID2CommunityID($steam_id){
$parts = explode(':', str_replace('STEAM_', '' ,$id));
$communityID = bcadd(bcadd('76561197960265728', $parts['1']), bcmul($parts['2'], '2'));
return $communityID;
}
With that, I can make my list of comma separated community ids with this:
while ($row = $mysqli->fetch_assoc($request)) {
$ids .= ',' . SteamID2CommunityID($row['steamid']) . ',';
}
Now for the tricky part, all these values come back in one JSON array. I need to add something, so when I display my data, I can convert a 'steam_id' straight to a 'name' (with the existing array).
Example of an output (most keys & values are removed to make it readable)
Array (
[response] => Array
(
[players] => Array
(
[0] => Array
(
[steamid] => 76561198010207577
[personaname] => [rGA] Stainbow
)
[1] => Array
(
[steamid] => 76561197966653036
[personaname] => |K}{R|Mastarious(MNBH)
)
)
)
)
So again, how would I go about going straight from a 'steam_id' to a name?
Thank you to anybody who can provide code and/or suggestions!
This is a variant duplicate of another Stack Overflow question, which is more practical and less localized, but I might as well answer this.
Assuming that your input steam_id is $INPUT and your final output array is stored in $OUTPUT, this is the functional foreach approach that you could use to convert steam_id to personaname:
/**
* Convert steam_id to personaname
* #returns STRING The name associated with the given steam_id
* BOOL FALSE if no match was found
*/
function steamID_to_name($INPUT, $OUTPUT)
{
// This gets the relevant part of the API response.
$array = $OUTPUT['response']['players'];
// Using your function to convert `steam_id` to a community ID
$community_id = SteamID2CommunityID($INPUT);
// Linear search
foreach ($array as $array_item)
{
// If a match was found...
if ($community_id == $array_item['steamid'])
// Return the name
return $array_item['personaname'];
}
// If no match was found, return FALSE.
return false;
}

Categories