mongodb - search in subarray, PHP - php

i started with mongodb and played around with random temperature data
like this:
'weather' => array(
'Air' => array(
'Jan' => 11,
'Feb' => 20,
'Mar' => 24,
'Jun' => 28,
'Jul' => 30
)
),
Now my question:
How can i query the Air array ?
I knwo i can do somethin like:
$query = array('weather.Air.Jan' => 11);
Works fine...
But how can i search in the whole Air array:
$query = array('weather.Air.$' => 40);
This query doesn't work...
Can somebody help me

Unfortunately, the query you're looking for does not exist.
As written, you're asking for "weather.Air where a key in the JSON object contains a value of 40".
MongoDB has the ability to "drill into" arrays. However, when it comes to sub-objects, you have to reach into the keys directly. There is no operator that provides a "search all keys" method. There is an outstanding JIRA request for this item right here.

Related

Trying to merge two results of SQL queries - ToDoList App

I am trying to merge two results of two queries in MYSQL using PHP, but I am puzzled how to do it! I am using PDO. I am programming for a hobby and am trying to make a to do list app just like a Trello board. However, I just can't figure out how to merge two results from different tables in a database.
The idea is as follows:
I have a table called 'task_lists' with the content:
'list_id => 1, list_name = 'listOne'
'list_id => 2, list_name = 'listTwo'
And a table called 'tasks':
task_id => 1, list_id => 1, task_name => 'taskOfListOne', duration => 5, is_done => 1
task_id => 2, list_id => 1, task_name => 'anotherTaskOfListOne', duration => 5, is_done => 1
task_id => 3, list_id => 2, task_name => 'taskOfListTwo', duration => 10, is_done => 0
And I am trying to create an array that is merged between the two results as something like:
(I know this is a rough picture of how the array is supposed to look like)
$result = [array]
[list_id] = 1, [list_name] = 'listOne' =>
[array][list_id] = 1, ['task_name] = taskOfListOne,[duration] = 5, ['is_done'] => 1
[array][list_id] = 1, ['task_name] = anotherTaskOfListOne,[duration] = 5, ['is_done'] => 1
[list_id] = 2, [list_name] = 'listTwo' =>
[array][list_id] = 2, ['task_name] = taskOfListTwo,[duration] = 5, ['is_done'] => 1
Is this even possible? I have tried a Union sql query and methods like nested foreach statements, but none of them worked for me. Am I missing something here?
PS: Sorry for my bad english.
Have you tried a left join?
SELECT TL.`list_id`, TL.`list_name`, T.`task_name`, T.`duration`
FROM task_lists AS TL
LEFT JOIN tasks as T ON TL.`list_id` = T.`list_id`
And then in PHP you build the array in the format you want.
Later edit:
Simple PHP example to parse SQL data as you asked (to remove duplicated info):
<?php
// $mysql_rows -> here is your query result, fetched as associative array
$filtered_array = array();
foreach ($mysql_rows as $row){
// Initiate record if is not already initiated
if (!isset($filtered_array[ $row['list_id'] ])){
$filtered_array[ $row['list_id'] ] = array(
'list_id' => $row['list_id'],
'list_name' => $row['list_name'],
'tasks' => array()
);
}
// Add tasks
$filtered_array[ $row['list_id'] ]['tasks'][] = array(
'task_name' => $row['task_name'],
'duration' => $row['duration'],
'is_done ' => $row['is_done ']
);
}
// Optional: if you want to remove list_id from $filtered_array key names, uncomment the next line
// $filtered_array = array_values($filtered_array);
?>

MySQL result multiple arrays

i.e : i have 2 tables
Product ( id, name )
Photo ( id, name, photo_id )
And I need to get result in array like this:
array(
'id' => 1,
'name' => product,
'photos' => array(
array('id' => 1, 'name' => 'photo1')
array('id' => 2, 'name' => 'photo2')
)
}
Is it possible in PHP using clear SQL?
I know that is possible to get 2 arrays and connect it but I have many records and I dont want to wase time to quering.
You have to add a foreign_key in your photo table "product_id".
Then create a method getPhotos() in your Product class with will collect all photos for your product.
Is it possible in PHP using clear SQL?
Not in a single SQL call. With a single call, this is the closest you can get:
array(
'id' => 1,
'name' => product,
'photo_id' => 1,
'photo_name' => 'photo1')
),
array(
'id' => 1,
'name' => product,
'photo_id' => 2,
'photo_name' => 'photo2')
)
Your only choice for the format you want is to run queries separately or to combine them into the data structure you want.
As mentioned, this is not possible with SQL. SQL is based on the relational model which is a 1-Normal-Form data model. That means, the result relation is also flat (no nested relations in a relation).
However, there are good frameworks which generate intermediary models in your corresponding target language (e.g. Python, Java, ...) that circumvent the impression of a flat data model. Check for example Django.
https://docs.djangoproject.com/en/1.8/topics/db/models/
Moo

make multilevel array from mysql php

i have this array in an example, how can i get the same result from query from database?, i need to replace the values which the values of the database.
$data = array(
array(
'qty' => 1,
'Price' => 1.00,
'total' => 1.00
),
array(
'qty' => 2,
'Price' => 1.00,
'total' => 2.00
),
array(
'qty' => 3,
'Price' => 1.00,
'total' => 3.00
)
);
then in the example use the nusoap lib
foreach($data as $concept) {
$par['Concepts'][] = new soapval('Concept', 'Concept', $concept);
}
so i need to call the query:
$query_data_cot = mysql_query("SELECT * FROM data WHERE id='1'");
while($data_quote=mysql_fetch_array($query_data_cot)){
$conceptosDatos[]["qty"]=$data_quote['qty'];
$conceptosDatos[]["Price"]=$data_quote['price'];
$conceptosDatos[]["total"]=$data_quote['total'];
}
but when i do these i got an error
Error: Array ( [faultcode] => soap:Server [faultstring] => Server was unable to process request. --->
thank you
Everytime you use $conceptosDatos[]... the [] will create a new subarray. So your result will be something like this
array(
array('qty' => ..),
array('Price' => ..),
array('total' => ...),
array('qty' => ..),
array('Price' => ..),
array('total' => ...),
...
)
Instead you need to create a new subarray only for a whole set, so use something like this
$query_data_cot = mysql_query("SELECT qty, price, total FROM data WHERE id='1'");
while($data_quote=mysql_fetch_assoc($query_data_cot)){
$conceptosDatos[] = $data_quote;
}
Of course you could also do it like this
$query_data_cot = mysql_query("SELECT qty, price, total FROM data WHERE id='1'");
while($data_quote=mysql_fetch_assoc($query_data_cot)){
$conceptosDatos[] = array(
'qty' => $data_quote['qty'],
'Price' => $data_quote['price'],
'total' => $data_quote['total'],
);
}
But why write every field if you're going to copy the whole array anyway?
If you need to use different names (as in your example price and Price), you can either change your db schema or use aliases in your query, giving you this code:
$query_data_cot = mysql_query("SELECT qty, price AS Price, total FROM data WHERE id='1'");
while($data_quote=mysql_fetch_assoc($query_data_cot)){
$conceptosDatos[] = $data_quote;
}
This has the advantage that if you wish to modify your code in the future, you'd only need to modify the query (and could probably encapsulate this logic inside a function) - so less work for future you.
By the way, did you see the big red box in the manual on all mysql_* methods's sites? It's deprecated and PDO as well as MySQLi are way better alternatives. This helps decide what to use.
Try this , while($data_quote=mysql_fetch_array($query_data_cot , MYSQL_ASSOC )) , as you are retrieving the $data as an associative array .
Each assignment line in your loop is creating a new element of the $conceptDatos array, not filling in a different element of the same element. So your array looks like:
array(
array('qty' => 1),
array('Price' => 1.0),
array('total' => 1.0),
array('qty' => 2),
array('Price' => 1.0),
array('total' => 1.0),
...
)
Your loop shoud be:
while($data_quote=mysql_fetch_array($query_data_cot)){
$conceptDatos[] = array(
'qty' => $data_quote['qty'],
'Price' => $data_quote['price'],
'total' => $data_quote['total']
);
}

Array in a Array SOAP V2 (WS-I Compliance Mode)

$result = $proxy->salesOrderInvoiceCreate((object)array('sessionId' => $sessionId->result, 'itemsQty' => array('order_item_id' => 15, 'qty' => '1')));
$mainarray[];
$itemarray[];
I need multiple of this
array('order_item_id' => 15, 'qty' => '1')
Which means i need a array in a array.
foreach(statement){
array_push($itemarray, "order_item_id", echo $item->product_id;);
array_push($itemarray, "qty", echo $item->qty);
array_push($mainarray, $itemarray);
}
enter code here
Request Example SOAP V2 (WS-I Compliance Mode)
http://www.magentocommerce.com/api/soap/sales/salesOrderInvoice/sales_order_invoice.create.html
In fact i'm also not sure what do i replace the current
array('order_item_id' => 15, 'qty' => '1')
with
array($mainarray) ??
That is not the correct way of using array_push your current $itemarray output will look something like
Array
(
[0] => 'order_item_id'
[1] => '200'
[2] => 'qty'
[3] => '2'
)
I would go back to basics and use something like to generate your multi dimensional array:
$itemarray[] = array("order_item_id" => $item->product_id, "qty" => $item->qty);
array_push($mainarray, $itemarray);
Edit:
Ok I reread your questions, ignore $mainArray.
$result = $proxy->salesOrderInvoiceCreate((object)array('sessionId' => $sessionId->result, 'itemsQty' => $itemarray));
That should work as with the other examples qty/itemsQty show it accepting multikey arrays.

PHP: How will array depth influence performance?

Now I know there is some related questions on this topic but this is somewhat unique.
I have two array structures :
array(
[0] => array(
'stat1' => 50,
'stat2' => 12,
'stat3' => 0,
'country_name' => 'United States'
),
[1] => array(
'stat1' => 40,
'stat2' => 38,
'stat3' => 15,
'country_name' => 'Ireland'
),
[2] => array(
'stat1' => 108,
'stat2' => 0,
'stat3' => 122,
'country_name' => 'Autralia'
)
)
and the second
array(
'stat1' => array(
'countries' => array(
'United States' => 50,
'Ireland' => 40,
'Autralia' => 108,
)
)
),
'stat2' => array(
'countries' => array(
'United States' => 12,
'Ireland' => 38,
)
)
),
etc...
The second array can go even to level 4 or 5 if you add the cities of those respective countries. Further to note is that the second array structure will have no 0 data fields (note that in the second one australia is not there because it is 0) but the first structure will have a whole whack of zeros. Also note that the second structure will have duplicates i.e. 'United States'
My question is this: How does these array structures compare when they are json_encode() and used in a POST ajax request? Will the shallow depth array, with it's whack of zeros be faster or will the better structured array be better in terms of size?
I have done some testing and for a finite dataset the difference in the output data - (I outputted the data into a text file) between the two is insignificant really.
Array structure 1 - All city and country data outputs to 68kb
Array structure 2 - All city and country data outputs to 71kb
So there is a slight difference but it seems that the difference is insignificantly small when taking into account that the data is in JSON format and used in an AJAX request to the google visualization geomap API.
I haven't tested the micro times in loading difference but for a user to look at a loading .gif image for 0.0024microseconds (i'm shooting a random time for the sake of argument) does not make a big dent in usability either way. Thanx all for you comments

Categories