Iterating through numeric array with PHP mustache - php

I'm using mustache to handle the frontend of my PHP, and I can't find a way to iterate through a numeric array:
From an API y have something like:
data =>
array (size=2)
50 =>
array (size=2)
'appid' => int 50
'name' => string 'Half-Life: Opposing Force' (length=25)
70 =>
array (size=2)
'appid' => int 70
'name' => string 'Half-Life' (length=9)
I need to print the appid and name of each app but I cant make it work
I tested the Implicit iterator but it seems to be for printing strings, for example, this doesn't work:
{{#data}}
{{#.}}
{{appid}}: {{name}}
{{/.}}
{{/data}}
If you have any idea of how to make this work, it would be appreciated, also if I can get recommendations for another library like mustache for PHP it would be awesome

Related

how to access fields in mongo document

I have a php codeigniter web app that has a mongo db backend.
i'm stuck for now using the mongoclient library for php.
I often have to run commands like this:
$result = $collection->find(
array("didnum" => $didnum)
);
$result = iterator_to_array($result);
Assuming that $result looks like this:
array (size=1)
'5824b9376b6347a422aae017' =>
array (size=10)
'_id' =>
object(MongoId)[22]
public '$id' => string '5824b9376b6347a422aae017' (length=24)
'users' =>
array (size=1)
0 =>
array (size=2)
...
'rules' =>
array (size=1)
0 =>
array (size=5)
...
'id' => string '5824b9376b6347a422aae017' (length=24)
'last_assigned' => string 'missing' (length=7)
'widgetnum' => string '+18455100023' (length=12)
'location' => string 'missing' (length=7)
What is the easiest way to access the location field?
In other words, in cases where I know there will only be one result, I'm still finding that i have to loop through $result because the array is an associative one, and i won't know what the ID is.
Just wondering if there's an easier way to do this?
Thanks.
I'm not very much into PHP, but findOne method seems to exist for PHP binding as well as other languages' bindings
You can use $collection->findOne instead of $collection->find

PHP - retrieving and parsing this JSON file

I'm looking for a way to access this JSON file data. What I'm interested in is to extract the property named documentjsonblob, as below.
object(Quadrem\Model\Order)[201]
protected '_dateCreated' => null
protected '_buyerCode' => null
array (size=2)
2415 =>
array (size=23)
'#storeid' => string '813' (length=3)
'#active' => string '1' (length=1)
'#created' => string '2013-11-25 12:28:21' (length=19)
'documentjsonblob' => string '{"HEAD":{"ORDERSEQUENCE":"0","TOTAL_TAX":7.9,"TOTAL_AMOUNT":86.9,"NUMBER":"AKMon3","TYPE":"NB","TYPE_NAME":"Standard PO","SUPPLIER":"0000002122","CREATED":"2013-04-29T12:00:00Z","CONTRACT_NUMBER":"","EXTERNAL_REFERENCE":"","CONTACT_PERSON":"Caroline Howlett","COMMENT":[""],"CURRENCY":"AUD","DELIVERY_TERMS":"DeliveryCondition|","PAYMENT_TERMS":[{"TEXT1":"21st day of next month after receipt"}],"NET_VALUE":79.0,"DELIVERY_ADDRESS":{"NAME_1":"KGTP FACILITY","NAME_2":"GAS TREATMENT PLANT","NAME_3":"KGPF","POSTAL_CODE":"6714","CITY":"Karratha","STREET":"Withnell Bay","REGION":"AUWA","REGION_NAME":"AUWA","COUNTRY":"AU"}]}' (length=3029)
'documenttype' => string 'PO' (length=2)
1890 =>
array (size=23)
'#storeid' => null
'#active' => null
I'm not quite sure which kind of an encoded JSON file this is by the way it looks. Would appreciate it if somebody could help.
Thanks.
Since in the comment you have mentioned it is the out put of var_dump and you want to get documentjsonblob, let's follow this:
On first line you have object(Quadrem\Model\Order)[201], that means you var_dumped an object, say $my_obj
On line four array (size=2) says you have an array, and what you need is located in the first element of the array, so $my_obj[0]
$my_obj[0] holds an associative array, and the desired index is documentjsonblob, so we can get the String representation as:
$my_arr = $my_obj[0];
$json_str = $my_arr['documentjsonblob'];
Now $json_str holds the String representation, to convert it to an PHP object:
$json_obj = json_decode($json_str);
So now $json_obj holds the object you want.

Iterator that assigns subvalue as key

Currently I'm looping through a quite large data set. This multidimensional array needs to be grouped by specific array values of its sub arrays. As this is a holiday project, I want to do deepen my knowledge and make more use of PHPs Iterators. Point is, that I don't know how to transform a numeric multi-dimensional Array into a multi-dimensional array with associative keys.
Shortened example (GeoJSON to Array)
array (size=4)
'type' => string 'FeatureCollection' (length=17)
'features' => // THIS is the actual array
array (size=207)
0 => // Sub-Arrays like this one are repeating
array (size=5)
'type' => string 'Feature' (length=7)
'geometry' =>
array (size=2)
'type' => string 'LineString' (length=10)
'coordinates' =>
array (size=410)
0 =>
array (size=2)
0 => float 16.359980888872
1 => float 48.208437070943
// etc.
'geometry_name' => string 'SHAPE' (length=5)
'properties' =>
array (size=5)
'OBJECTID' => int 273
// This/"LBEZEICHNUNG" is the part I want to order/summon
// all further "geometry"-parts by
'LBEZEICHNUNG' => string '13A, 2, 86, U3' (length=1)
'LTYP' => string '1' (length=1)
'LTYPTXT' => string 'Tramway' (length=12)
'SE_ANNO_CAD_DATA' => null
'id' => int 1
The features array is what holds the actually looped datasets. And LBEZEICHNUNG are the values (single or comma separated) I want to sort/order by.
To make an example:
// Original values:
'LBEZEICHNUNG' => string '13A, 2, 86, U3'
// Now split them and push the features into new keys that have those values:
'13A' => array(
0 => // Sub-Arrays like this one are repeating
array (size=5)
'type' => string 'Feature' (length=7)
'geometry' =>
array (size=2)
'type' => string 'LineString' (length=10)
'coordinates' =>
array (size=410)
0 =>
array (size=2)
0 => float 16.359980888872
1 => float 48.208437070943
// etc.
'geometry_name' => string 'SHAPE' (length=5)
'properties' =>
array (size=5)
// "OBJECTID" now is obsolete
// "LBEZEICHNUNG" is now obsolete
'LTYP' => string '1' (length=1)
'LTYPTXT' => string 'Tramway' (length=12)
'SE_ANNO_CAD_DATA' => null
// "id" now is obsolete as well
),
"2" => // gets the same values as "13A"
// same goes for "86" and "U3"
Now every sub array that would have either 13A, 2, 86 or U3 in ["properties"]["LBEZEICHNUNG"], would push its geometry to the end of the already existing subarray/sub-Iterator.
So far I only got a basic recursive Iterator set up, that runs through all leaves.
$data = new \RecursiveArrayIterator( $fileContents );
foreach( new \RecursiveIteratorIterator( $data ) as $key => $value )
{
// foo. bar. dragons.
}
Point is that I can't really figure out how to assign new keys from values in the Iterator. I already tried using a RecursiveFilterIterator and failed gracefully as its simply not intended to do this. Quite frankly: I'm lost as I either can't find the right Iterator to use or I simply ain't know enough about Iterators yet.
I got a working solution with nested foreach-es pushing into another Array. As this is my holiday project I want to learn, hence the Iterator solution, which I hope is more maintainable in the long turn.
Edit: Link to the original Geo-JSON data set CC-BY-SA 3.0/AUT - Data provided by the City of Vienna. Other formats can be found here.
If I understood correctly, you want to sort/ or group the array based on that "LBEZEICHNUNG" key, and use PHP iterators. In order to do that, you have to traverse the entire array, and build a new one that holds the values grouped by that key. This is simple foreach logic.
Iterators shine when you want to traverse a data collection and fetch the data during traversal (or alter it).
In this case, you are fetching the data outside of the iterator (json_decode ?), so that makes iterators kind of pointless - unless you need to do more than just sorting. If you do, I'd suggest you store that data in a format that allows you to easily fetch sorted sets, like a database, then you can use iterators to their full potential.
One way to group the routes is to use basic OOP:
class Route{
protected $trams = array();
// add other route properties (type, geometry etc.)
public function assignTo(Tram $line){
if(!in_array($line, $this->trams, true))
$this->trams[] = $line;
}
public function getTrams(){
return $this->trams;
}
}
class Tram{
public $name;
protected $routes = array();
public function __construct($name){
$this->name= $name;
}
public function addRoute(Route $route){
$this->routes[] = $route;
$route->assignTo($this);
}
public function getRoutes(){
return $this->routes;
}
}
Example:
$trams = array();
foreach($data as $routeData){
$route = new Route();
$tramNames = explode(', ', $routeData['features']['properties']['LBEZEICHNUNG']);
foreach($tramNames as $name){
if(!isset($trams[$name]))
$trams[$name] = new Tram($name);
$trams[$name]->addRoute($route);
// set other route properties...
}
}
You can use usort to sort your multi-dimensional array based on sub-values:
$JSON = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode(file_get_contents("http://data.wien.gv.at/daten/geoserver/ows?service=WFS&request=GetFeature&version=1.1.0&srsName=EPSG:4326&outputFormat=json&typeName=ogdwien:OEFFLINIENOGD")));
$geoarray = json_decode($JSON, true);
$myarray = $geoarray["features"];
function cmp($a, $b) {
return $a["properties"]["LBEZEICHNUNG"] - $b["properties"]["LBEZEICHNUNG"];
}
usort($myarray, "cmp");
print_r($myarray);

access associative array

I am using Code Igniter and I get following data structure after executing a query at DB
array
'application' =>
array
0 =>
object(stdClass)[19]
public 'app_id' => string '16' (length=2)
public 'app_name' => string 'dddddddd' (length=8)
public 'app_title' => string 'sdfsdf' (length=6)
public 'app_comments' => string 'sdfsdf' (length=6)
public 'active_flg' => string 'N' (length=1)
I know one way to access the values is
foreach($application as $key => $value)
$value->app_id
But I know that I will get only one record each time so I want to access the elements without using foreach.
I have tried to $application->app_id and $application['app_id'] but I keep getting error.
Can anybody please help me to understand how to access the data directly??
You are using multidimensional mixed type of array, with numeric indexing on the second level. SO, while accessing the values, you have to use them too. Like
echo $array['application'][0]->app_id;
A simple example to show you the structure of your array and how you might access it...
$objArray = array('app_id' => 7, 'app_name' => 'apps demo', 'app_title' => 'apps demo title');
$applicationArray = array('application' => array((object)$objArray));
// access the array
print $applicationArray['application'][0]->app_id;
Are you getting that result by doing the following?
$res = $this->db->query('select * from application limit 1')->result();
If so, you can put that result into an object by doing:
$app = $this->db->query('select * from application limit 1')->row();
This way you can access the properties as follows:
echo $app->app_id;
You should check out codeigniters manual on getting results.

How to get content from array

I'm total newbie to PHP and Drupal but I fix this simple(?) thingo on my template. I want to get title, date, text and link path from this array? I can't get it out of there. I think its because its in inside of another array and because im noob in PHP I cant get it out of there ? Also I would like to get it to a loop. If theres more content, I would get it as a list or something. I would use foreach for this? Like foreach $contents as $content and so on?
I get this output from this: var_dump($contents);
array
'total' => string '1' (length=1)
'data' =>
array
0 =>
array
'cid' => string '13231' (length=3)
'title' => string 'TITLEBLABLABLA' (length=3)
'body_text' => string 'TEXTBLABLABAL' (length=709)
'created' => string '313131' (length=10)
'created' => string '2010-07-13 14:12:11' (length=19)
'path' => string 'http://goog.fi' (length=72)
Think of accessing multidimensional arrays in the same way you'd access a file in a subdirectory: just reference each level/directory in sequence. Assuming that array is stored in $arr, you'd get the title as follows:
$arr['data']['0']['title']
Here is a basic PHP array tutorial
It comes down to this:
You retrieve an element of an array with []
$array = array( 'a' => 'b');
echo $array['a']; //Prints b;
To loop through a multi-dimensional array and echo date try this...
foreach ($contents as $key => $content) {
echo $content[$key]['created'];
}
If that doesn't work, post the output of print_r($content) in your question so I can't build you exact array. I'm kinda confused over the structure of your array in your question.

Categories