PHP - Convert foreach to arrays - php

Anyone can help me
I have a little problem with the following code
foreach ($products as $product) {
$product->name;
$product->code;
...
}
My output code with var_dump($products)
array
0 =>
object(stdClass)
...
...
...
1 =>
object(stdClass)
...
...
...
And I need output something like this
$output = array(
array('name' => 'item1', 'code' => 'code1', 'price' => '10.00'),
array('name' => 'item2', 'code' => 'code2', 'price' => '20.00')
);

For this purpose, there is a function is php json_decode()
mixed json_decode ( string $json [, bool $assoc = false [, int $depth
= 512 [, int $options = 0 ]]] )
Need to use this function sensibly.
As you see in the function description,
The function's three parameters:
1) Variable to be converted.
2) Return as associative array.
3) Depth: default => 512. Means upto depth of 512 levels (in case of multi-dimensional array or complex object), the child elements will be converted into arrays if second parameter is set to true.
First encode your variable by json_encode() and the decode it with using
json_decode().
json_decode() 's second parameter should be set to true.
This true means return associative array instead of original type.
Pseudo code:
$output = json_decode(json_encode($yourVar), TRUE);

Related

Extract just the strings from an array_column array return

I've got told many times, if there is a new question even on the same code to just create a new thread so here I am. Thanks to the guys for helping me with the previous question.
I have the following code:
/* Return an array of _octopus_ids */
$offices = array_map(
function($post) {
return array(
'id' => get_post_meta($post->ID, '_octopus_id', true),
);
},
$query->posts
);
/* Dump out all the multi-dimensional arrays */
var_dump($offices);
$test = array_column($offices, 'id');
var_dump($test);
var_dump($offices) dumps the following:
array (size=10)
0 =>
array (size=1)
'id' => string '1382' (length=4)
1 =>
array (size=1)
'id' => string '1330' (length=4)
var_dump($test) dumps the following:
array (size=10)
0 => string '1382' (length=4)
1 => string '1330' (length=4)
Problem:
How can I use the following code:
$results = $octopus->get_all('employees/' . $test; which results in an Notice: Array to string conversion error.
I want to be able to make a results call such as this $results = $octopus->get_all('employees/1382'); - So I want just the numeric string of $test to be appended to the end of employees/
If I hardcode the 1382 after employees/, I get the following result:
object(stdClass)[1325]
public 'id' => int 1382
What's the proper way to array of strings into just strings?

2-dimensional array to 1-dimensional array convertion

With my code:
$sql = "SELECT number.phone_number FROM number, ordered_number WHERE ordered_number.number_id=number.id AND ordered_number.order_id=$id";
$connection = \Yii::$app->getDb();
$command = $connection->createCommand($sql);
$numery = $command->queryAll();
I get array that looks like this:
array (size=3)
0 =>
array (size=1)
'phone_number' => string '546732354' (length=9)
1 =>
array (size=1)
'phone_number' => string '565345456' (length=9)
2 =>
array (size=1)
'phone_number' => string '456557546' (length=9)
I want to get simple array, where the first element is just the number (here - the string), without name 'phone_number' and additional 1-element arrays inside the main array. When I try to do foreach on this array, it tells me that I use "Illegal offset type". I found that it means I'm using object, instead of an array, but that's an array, not an object and I have no idea what to do.
Even simplier (but for php5.5 and php7):
$numery = array_column(
$command->queryAll(),
'phone_number'
);
Use below loop to get desired result
$numery = $command->queryAll();
$number_arr = array();
foreach($numery as $number)
{
array_push($number_arr,$number['phone_number']);
}
print_r($number_arr);

Confusion with JSON_DECODE second param

I just created a small program to check JSON and JSON_FORCE_OBJECT
$tree = [
0 => array
(
'id' => 1,
'parent' => '0',
'name' => 'b',
'surname' => 'myfolder/b'
),
1 => array
(
'id' => 2,
'parent' => 1,
'name' => 'ignore',
'surname' => 'myfolder/ignore2'
),
2 => array
(
'id' => 3,
'parent' => 1,
'name' => 'ignore2',
'surname' => 'myfolder/ignore4'
)
];
var_dump($tree);
$try = json_encode($tree);//To print with key. Also if we decode we get result as object
//echo $try;
echo '<br />';
$try2 = json_decode($try,JSON_FORCE_OBJECT);
var_dump($try2);
$try2 is exactly equal to $tree an associative array.
Whereas if I remove JSON_FORCE_OBJECT from this line
$try2 = json_decode($try,JSON_FORCE_OBJECT);
I get an array with child object. Though JSON_FORCE_OBJECT is supposed to be used with json_encode but using it with json_decode, I get a surprising result. I am unable to understand whats going on inside?? I thought when I encode it and decode it I should get same result. But I got the same result only when I used JSON_FORCE_OBJECT. Can anyone please help why this happens?
According to the manual: http://php.net/manual/en/function.json-decode.php
json_decode returns an array of objects if you want to convert them in assoc array you should specify the second param which is a boolean
JSON_FORCE_OBJECT is an int with value 16...
when this is passed as second param php cast/converts it to its bool equivalent which true.
To test the above stated behavior try:
var_dump((bool)1; (bool)2, (bool)16)
//output bool(true) bool(true) bool(true) .
var_dump((bool)0)
//outputs bool(false)
So it's nothing to do with JSON_FORCE_OBJECT...even
json_decode($try,true);
json_decode($try,2);
json_decode($try,3);
json_decode($try,4);
json_decode($try,'someVar');
....
//should return your expected result (assoc array)
Similarly if you pass 0 as second param PHP will cast it into bool (which is false) and returns you an object
json_decode($try,0);
json_decode($try,false);
json_decode($try,null)
json_decode($try)
...
//will return objects
The second parameter to json_decode is a boolean. It accepts true or false. It does not accept JSON_FORCE_OBJECT. You're trying to use the wrong constant for the wrong function.
json_decode's 4th parameter accepts a bitmask of constants, but currently it only supports JSON_BIGINT_AS_STRING.
If you want to return stdClass instances for JSON objects from json_decode, set its second parameter to false (the default). Setting it to any non-falsey value makes it return associative arrays instead of objects. Setting it to JSON_FORCE_OBJECT counts as "not-falsey".
It's all described in the manual: http://php.net/json_decode

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);

Accessing an array inside of an array

When trying to access an array inside an array, only NULL is output.
My Code:
$aStats = array();
$aStats['hd'] = array();
$aStats['hd'][] = array
(
'dev' => $device,
'total' => $total,
'used' => $used,
'free' => $free,
'used_perc' => $used_perc,
'mount' => $folder
);
echo $aStats['hd']['free'];
When using json_encode, the values are displayed correctly:
die( json_encode( $aStats ) );
Where is my mistake?
Replace these lines:
$aStats['hd'] = array();
$aStats['hd'][] = array
With this:
$aStats['hd'] = array
You appear to be accessing your array ($aStats['hd']['free'];) as if the value of hd is an associated array, but using [] creates a new integer index in the array, and stores the value in that index. Joe Walker's answer shows what happens instead, that you have an associative array pointing to an indexed array pointing to another associative array, rather than the associative to associative array you suggest you're trying to use in your echo statement.
This is a practical tip that will let you find out where is the issue easly, all you need to do is:
var_dump($aStats);
This will output:
array (size=1)
'hd' =>
array (size=1)
0 =>
array (size=6)
'dev' => string 'SomeDevice' (length=10)
'total' => string '10000' (length=5)
'used' => boolean true
'free' => boolean false
'used_perc' => string 'none' (length=4)
'mount' => string '/some/directory/here/' (length=21)
Now you know you can access this element using
$aStats['hd'][0]['free'];
This will return null in your question because your variables are not yet initialized, but I guess you do have them initialized in your code, hope this helps.

Categories