I'm trying to get records from a table using a given ID and I want to store specific columns into another array but I'm getting null every time I var_dump() my array.
My code:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$getOrder[] = array(
array($ordersInWaypoints),
array(Order::where('id', '=', $ordersInWaypoints)->get()->lists('tracking_id')),
array(Order::where('id', '=', $ordersInWaypoints)->get()->lists('shipper_ref_no'))
);
}
For those wondering where $ordersInWaypoint came from, I retrieved that from here:
$ordersInWaypoint = array();
ordersInWaypoint = Transaction::where('waypoint_id', "=", $firstWaypoint)->get()->lists('order_id');
Don't mind the $firstWaypoint since that is determined by user input.
Everytime I var_dump($getOrder); I get the following result set:
array (size=1)
0 =>
array (size=3)
0 =>
array (size=1)
0 => int 637
1 =>
array (size=1)
0 =>
array (size=1)
...
2 =>
array (size=1)
0 =>
array (size=1)
...
The first element is correct, but the rest return empty sets.
I think you're getting no value because those Order::where(...) return Eloquent objects, not just single values.
You could better try this way:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$order = Order::where('id', '=', $ordersInWaypoints)->get();
$getOrder[] = array(
array($ordersInWaypoints),
array($order->tracking_id),
array($order->shipper_ref_no)
);
}
Let me know if this fixes it ;)
Edit
It's even better if you don't use a multidimensional array as you need just these three values, so the final code becomes:
$getOrder = array();
foreach($ordersInWaypoint as $ordersInWaypoints)
{
$order = Order::where('id', '=', $ordersInWaypoints)->get(); // create Eloquent object from query
$getOrder[] = array(
$ordersInWaypoints,
$order->tracking_id, // Calls column value as method from the Eloquent object
$order->shipper_ref_no // Same (you could also call it as an array,
); // in that case you would type $order['shipper_ref_no']
}
Related
I wish classify the values of my table in ascending order to be able to use them in a variable $distancecp.
My var_dump finds my values well but I can not classify them in ascending order.
$select100=mysqli_query($conn,$select10);
while($asso = mysqli_fetch_assoc($select100)) {
$distancecp1 = getDistance(''.$villeselect.', '.$cpselect.'',''.$asso['ville'].', '.$asso['codep'].'');
$distancecp2 = array($distancecp1);
var_dump($distancecp2);
foreach($distancecp2 as $distancecp) {
}
}
Results of var_dump($distancecp2) :
array (size=1)
0 =>
object(SimpleXMLElement)[8]
public 0 => string '68526' (length=5)
array (size=1)
0 =>
object(SimpleXMLElement)[10]
public 0 => string '71824' (length=5)
array (size=1)
0 =>
object(SimpleXMLElement)[7]
public 0 => string '67536' (length=5)
array (size=1)
0 =>
object(SimpleXMLElement)[9]
public 0 => string '33902' (length=5)
I tried :
$select100=mysqli_query($conn,$select10);
while($asso = mysqli_fetch_assoc($select100)) {
$distancecp1 = getDistance(''.$villeselect.', '.$cpselect.'',''.$asso['ville'].', '.$asso['codep'].'');
$distancecp2 = array($distancecp1);
asort($distancecp2);
foreach($distancecp2 as $distancecp){
echo ''.$distancecp.' ';
}
}
My echo returns me well my 4 values but not ranked in ascending order :(
Look carefully at your var_dump output: it's not printing a list of all your results, but is called multiple times, each time saying "array (size=1)". That "size=1" is your clue: you have a list with one thing in it, created with array($something). If you sort a list with one thing in it, you will just get the same list, with the same thing in it.
What you need to do instead is create one array for the whole loop, and add all the items to it:
$results = array();
while ( ... ) {
$distancecp1 = ...
$results[] = $distancecp1;
}
var_dump($results);
Then:
see here for appropriate sorting methods: How can I sort arrays and data in PHP?
to turn a SimpleXMLElement object into just a value, you write (string)$element
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);
I'm sure I must be doing something wrong, but I can't seem to find an answer anywhere (at least neither in the documentation nor on SO as of yet). I am a beginner in PHP and SQL.
I have this simple table called "mObject_has_media" with only two columns "media_idMedia" and "mObject_idmObject"
When I try to query the table with this code,
public function selectMediaIds (MObject $object) {
$medias = array ();
$req = $this -> _db -> query ('SELECT media_idMedia FROM mObject_has_media WHERE mObject_idmObject = ' . $object -> id ());
while ($data = $req -> fetch (PDO::FETCH_ASSOC)) {
$medias[] = $data;
}
$req -> closeCursor ();
return $medias;
}
the problem is this: when I var_dump the contents of the method's result, I get:
array (size=2)
0 =>
array (size=1)
'media_idMedia' => string '52' (length=2)
1 =>
array (size=1)
'media_idMedia' => string '53' (length=2)
I'd like to get rid of those nested arrays and just get something like:
array (size=2)
0 => 'media_idMedia' => string '52' (length=2)
1 => 'media_idMedia' => string '53' (length=2)
so I can simply run this array into a foreach loop right afterwards... I'm sure that this problem has everything to do with the fetch() method, but in spite of experimenting with different options, I haven't been able to get the desired behavior.
A similar question (I think) was asked here: PDO::FETCH_ASSOC Does not return the correct table columns but the answer mentioned the Zend framework, and I am NOT using any framework at all, this is just vanilla PHP.
Let's create a multi-dimensional array just for testing purposes:
$array = array(
array('foo' => 'value1'),
array('foo' => 'value2')
);
Now consider the following code:
$result = array();
while ($row = array_shift($array)) {
// $row will contain one nested array at a time
$result[] = $row;
}
print_r($result);
$row is an array, and with the statement $result[] = $row;, you're pushing the entire array to $result thereby making it multi-dimensional.
This would output:
Array
(
[0] => Array
(
[foo] => value1
)
[1] => Array
(
[foo] => value2
)
)
Now, consider the following code:
$result = array();
while ($row = array_shift($array)) {
// $row will contain one nested array at a time
$result[] = $row['foo'];
}
print_r($result);
With the statement $result[] = $row['foo'];, we are pushing the value $row['foo'] to the $result array. At the end of loop iteration, $result will hold an array of foo row values.
This would output:
Array
(
[0] => value1
[1] => value2
)
Demo
To fix your original code, you can modify it like so:
$medias[] = $data['media_idMedia'];
The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.
PDO::FETCH_ASSOC will return an array as shown in your code., except that if there are multiple columns with the same name, the value referred to by that key will be an array of all the values in the row that had that column name
I think this line of code
while ($data = $req -> fetch (PDO::FETCH_ASSOC)){ }
$data = $req -> fetch (PDO::FETCH_ASSOC)
`$data`, itself is returned as an array.
This means you don't need to define another array just use $data
Something like
$req = $this -> _db -> query ('SELECT media_idMedia FROM mObject_has_media WHERE mObject_idmObject = ' . $object -> id ());
while ($data = $req -> fetch (PDO::FETCH_ASSOC)) {
$data['media_idMedia']; //for media id.
}
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);
I like how CakePHP automatically loops through the results of MySQL queries and formats them in a nice map for you.
Here's a sample query that I'm using:
# Inside some model
return $this->query("
SELECT
Profile.id,
SUM( IF( HOUR(Log.event_one) > 3, 1, 0 ) ) as EventOne
FROM profiles Profile
JOIN logs Log ON Log.id = Profile.log_id
WHERE Profile.id = {$pUserId}
");
CakePHP would return a map like the following as the result:
array
0
array
'Profile'
array
'id' => 23
'0'
array
'EventOne' => 108
1
array
'Profile'
array
'id' => 23
'0'
array
'EventOne' => 42
2
...
What I'm trying to do is have the result be something like this:
array
'Profile'
array
'id' => 23
'Events'
# ^ I want to be able to specify this key
array
'EventOne' => 108
Any ideas?
You can't do that directly
The top level array keys are derived from the table name which mysql says the field relates to - in your case it's a calculated field and therefore (according to mysql) belongs to no table - hence the 0 array key.
Post processing
What you can do however, is post process the result so that it is the format you want:
public function getStuff() {
// The query call in the question can very easily be a normal find call
$return = $this->query("don't use query unless you have no choice");
foreach($return as &$row) {
$row['Events'] = $row[0];
unset($row[0]);
}
return $return;
}