how to get value in array from individual query - php

i have a
Book ID Array
Array
(
[0] => 61
[1] => 72
[2] => 78
[3] => 100
[4] => 102
)
now from another table table_bookPrice where price filed is given
i want that select all price from table_bookPrice where book id is in given array (book ID Array) and if price is not mentioned in table_bookPrice field then it would be automatic 500
what will be exact query
so the array i got is like this
Book Price Array
Array
(
[0] => 150
[1] => 100
[2] => 500 ( not mentioned in table, so it is 500)
[3] => 300
[4] => 200
)

I am at work so could not test or compile it, but I hope my logic is understandable.
Not sure if this will work but something along these lines
$book_price_array = array(); //contents to be added.
// loop through the array an examine its price by querying your table.
foreach ($book_id_array as $key => $value) {
$price = mysql_query("SELECT price FROM table_bookPrice
WHERE book_id = {$value}");
// there is a price, set the price.
if ($price > 0 && $price != NULL) $book_price_array[$key] = $price;
// there is no price, set the default price
else $book_price_array[$key] = 500;
}

Here's the test database I built for your problem:
mysql> select * from table_bookPrice;
+----+-------+--------+
| id | price | bookid |
+----+-------+--------+
| 1 | 150 | 61 |
| 2 | 100 | 72 |
| 3 | 300 | 100 |
| 4 | 200 | 102 |
+----+-------+--------+
4 rows in set (0.00 sec)
Here's the PHP code:
<?php
$books=array(61,72,78,100,102);
// establish an assoc array of bookid => default_price
$prices=array();
foreach($books as $bookid){
$prices["$bookid"]=500;
}
// build query to select all prices stored in database
$bookids=implode(', ',$books);
mysql_connect('localhost','aj','nothing') or die('unable to connect!');
mysql_select_db('books') or die('unable to select db!');
$stmt="SELECT bp.bookid, bp.price FROM table_bookPrice bp WHERE bp.bookid IN ($bookids)";
$res=mysql_query($stmt);
while( ($rec= mysql_fetch_assoc($res)) ){
$idstr=(string)$rec['bookid'];
$prices[$idstr]=$rec['price'];
}
print_r($prices);
?>
This outputs:
Array
(
[61] => 150
[72] => 100
[78] => 500
[100] => 300
[102] => 200
)

Related

Scoring system for collection of numbers (serial#)

I'm looking for a formula (PHP) that I can use to assign a score base on rarity of a number inside a collection. Serial#1 being the rarest.
For example, I have few sets of collections.
Collection 1 - Total number of items = 10 (Serial #1 to Serial #10)
Collection 2 - Total number of items = 100 (Serial #1 to Serial #100)
Collection 3 - Total number of items = 3500 (Serial #1 to Serial #3500)
Based on the 3 example sets. Collection 1 is considered the rarest collection because of only 10 items available in the set.
In addition to this. Each item is assigned with its serials, #1 being the best (rarest)
Here is the table of how I visualize the scoring system.
Collection 1
| Serial#| Score |
|:------:| :-----:|
| 1 | 1000 |
| 2 | 900 |
| 3 | 800 |
| 4 | 700 |
| 5 | 600 |
| 6 | 500 |
| 7 | 400 |
| 8 | 300 |
| 9 | 200 |
| 10 | 100 |
Collection 2
| Serial#| Score |
|:------:| :----:|
| 1 | 800 |
| 2 | 700 |
| 3 | 600 |
| 4 | 500 |
| ... | ... |
| 99 | 12 |
| 100 | 10 |
I just made up those scores just for representation.
With the tables above, Serial #1 in Collection 1 has a higher score compared to Serial #1 in Collection 2 because of the rarity of Collection 1.
I have few collections ranging from 1 of a kind (rarest of them all),10, 20, 150, 350, 1000, 5000, 10000, 50000” What “score” is this item supposed to get then?
for the rarest 1 of 1 the score will be based on the score of the
other Serial #1. If for example Collection with 10 items the serial#
get 1000 points then the 1 of 1 i can give 5000 points (this one no
need to calculate)
2. Are all the scores inside a collection supposed to add up to the same value?
No. It doesn't need to add up to the same value as the other collections
Your “made up” scores aren’t really helpful in explaining what kind of scoring logic you want to apply here in the first place
In the example table (made up scores). I just want to show that the different serial number scores. The higher serial number will have a lower score compare to the lower serial#. But the scores will differ from the other collections with the same serial number. Thus I categorized them by collections. Lower item count collections are considered rarer than those with higher item count.
4. But Serial #1 is supposed to have a higher score, than Serial #2, inside the collection? If so, then what would that be based on? Just the ascending order of those #1, #2, etc.?
Maybe it will be based on the ascending order.
5. All 10 items in collection 1 could get the same score?
No.
I don't have any preference on the score the serial number will get. I mean Serial #1 can get X score as long as it will be relative to the rarity of the collection. Serial #1 score will not be the same across collection unless they belong to the same collection rarity.
If I understand you correctly you want to count occurrences of score (value) and sort that occurrence count in a way that the lowest number (serial) will represent the values (score) that are the rarest and the higher the serial number is the value is more common.
For the:
Input Colleciton:
Array
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
[5] => 10
[6] => 10
[7] => 11
[8] => 11
[9] => 12
[10] => 12
[11] => 13
[12] => 13
[13] => 14
[14] => 14
[15] => 100
[16] => 100
[17] => 100
[18] => 101
[19] => 101
[20] => 101
[21] => 102
[22] => 102
[23] => 102
[24] => 103
[25] => 103
[26] => 103
[27] => 104
[28] => 104
[29] => 104
)
this code:
<?php
header('Content-Type: text/plain');
// generate colleciton
$collection = [];
# most unique values
$start = 5;
$end = 0;
for ($i = $start; $i > $end; $i--) {
$collection[] = $i;
}
# less unique values (2x the same values)
$start = 10;
$end = 15;
for ($i = $start; $i < $end; $i++) {
$collection[] = $i;
$collection[] = $i;
}
# least unique values
$start = 100;
$end = 105;
for ($i = $start; $i < $end; $i++) {
$collection[] = $i;
$collection[] = $i;
$collection[] = $i;
}
echo "Input Colleciton:\n";
print_r($collection);
# array of [value => how_many_occurences, ... => ...]
$valueCount = array_count_values($collection);
echo "Value count:\n";
print_r($valueCount);
$uniqueBins = [];
# convert to unique bins
foreach ($valueCount as $value => $key) {
$uniqueBins[$key][] = $value;
}
echo "Unique bins:\n";
print_r($uniqueBins);
// optionally sort by value
foreach ($uniqueBins as $key => $bin) {
asort($bin);
$uniqueBins[$key] = $bin;
}
echo "Unique bins after sort:\n";
print_r($uniqueBins);
generates the output:
Unique bins after sort:
Array
(
[1] => Array
(
[4] => 1
[3] => 2
[2] => 3
[1] => 4
[0] => 5
)
[2] => Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
)
[3] => Array
(
[0] => 100
[1] => 101
[2] => 102
[3] => 103
[4] => 104
)
)
Where values from the array under the key 1 are rarest and values from the array under the key 3 are most common.
The key number is not starting from zero but from 1 because values that are rarest have only single (1) occurrence in the whole collection.
If you want the output bin array to have keys starting from zero and continues in numbering (0,1,2,...) then use array_values(), this way:
$uniqueBins = array_values($uniqueBins);
at the end. By doing that you loose the information about the count (rarity) of values however you still have arrays of values in the order of their rarity (starting from most to the least)
To make this code work you need to have all values into single array $collection but if you have your values in multiple arrays then you can merge all of them into single $collection by using array_merge
Here are headlines to get you started....
Create a DB
Like this
Category :Rarest
uniqueid item name score
hashed#125 Dragon 1000000
hashed#122 Hydra 800000
hashed#100 Medusa 750000
Category :Rarer
uniqueid item name score
hashed other1 50000
hashed other2 30000
hashed other3 10000
Category :Rare
uniqueid item name score
hashed other1 5000
hashed other2 2000
hashed other3 800
This is how you can approach this...
0.hidden readonly checkbox[contains uniquehash] associate with clickable images[showing name of item]
1.[Connect to DB] mysql here
2.[query from tables (all uniqueids 1,2,3 and...)]
3.[from Post get user inputs as array][say user click image showing medusa and hydra - the hidden checkboxes send hashed#100 and hashed#122]
4.[foreach DB values as #strings]( unique ids are broken to individual strings)
5.[foreach user array as #strings]( uniqueids from userinputs are broken to individual strings)
6.[if user string match DB #strings](match each hash]
7.[return query [score] and [name of item] from where #string is found ](only matching ids return their score in this case score 800000 and 750000 as well as Hydra + Medusa)
8.[then [score for match1]] + [score for match2] + match 3 and so on]
(800000+750000)
echo [total score for user selections] + [names of items]
(1.55mil,hydra + medusa ) you can even show they are from the rarest collection
Since the beginning of the process the user in the frontend does not know what the item score is and there is no way to know they just get the total

Codeigniter Generate Dynamic Table Row Data

I am trying to load dynamic table data, my URI is;
example.coma/admin/view/form/<form_id>
My model query is;
public function getRecords($table, $form_id) {
$this->db->select('*');
$this->db->from($table);
$this->db->where('form_id', $form_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
This returns an array of data, I need to build a HTML table based on this array.
I'll show an example of two different arrays returned by the query.
Array 1.
(select * from members where form_id = 123)
Array
(
[0] => Array
(
[id] => 104
[member_no] =>
[firstname] => Peter
[lastname] => Keys
[address] => 17 main road
[email] => P3TER#HOTMAIL.CO.UK
[postcode] => UK123
[city] => London
[telnum] => 123123123
[fk_form_submission_id] => 123
)
)
Array 2.
(select * from orders where form_id = 123)
Array
(
[0] => Array
(
[colour] => blue
[type] => shirt
[age] => 34
[size] => medium
[quantity] => 2
[discount] => Y
[posted] => N
)
)
What I want to achieve is display a vertical table to display the dataset. Obviously each table will have different row names, example below;
Table 1.
+---------------+-------+
| ID | 104 |
+---------------+-------+
| Member Number | |
+---------------+-------+
| First Name | Peter |
+---------------+-------+
| Last Name | Keys |
+---------------+-------+
| etc | etc |
+---------------+-------+
Table 2.
+--------+--------+
| Colour | blue |
+--------+--------+
| P Type | shirt |
+--------+--------+
| Age | 34 |
+--------+--------+
| Size | medium |
+--------+--------+
| etc | etc |
+--------+--------+
How can I set these table row names? Do I need to create another array of table headers and merge both arrays?
Any advice is appreciated.
I'm not sure I fully understand - but if you want to set the keys of the array dynamiclly you can do that with foreach loop as:
<table>
<tr><th>Key</th><th>Value</th></tr>
<?php foreach($res[0] as $key => $val)
echo '<tr><td>'. $key . '</td><td>' . $val . '</td></tr>'; ?>
</table>
Edit:
If you want to change the keys name to something more displayable I would recommend using another array for swap (most of the time it done for translation...).
$displayName = array("id" => "ID", "member_no" => "Member Number", "firstname" => "First Name" ..., "type" => "P type", ...);
foreach($res[0] as $key => $val)
echo '<tr><td>'. $displayName[$key] . '</td><td>' . $val . '</td></tr>';
You can also use array_combine but that will need to know which kind of keys you have...
Notice that this solution will work only if the display name are unique for all kind of keys

Laravel - update multiple records with different values

I have a table , similar to this:
| key | value |
|----------|-------|
| limit | 15 |
| viplimit | 25 |
| .. | |
And i have an array :
Array
(
[0] => Array
(
[key] => limit
[value] => 10
)
[1] => Array
(
[key] => viplimit
[value] => 99
)
...
Now , saying we have 100 rows. What would be the best way to update the table corresponding to the array ?
There would be the option of a query for each 100 row, but that is just bad performance.
This should work:
$statement = "UPDATE mytable
SET key = CASE id
WHEN 1 THEN 'key'
WHEN 2 THEN 'another_key'
WHEN 3 THEN 'some_key'
END,
value = CASE id
WHEN 1 THEN 15
WHEN 2 THEN 25
WHEN 3 THEN 45
END
WHERE id IN (1, 2, 3)
");
DB::statement($statement);
Just think how to create correct query. If it's admin panel or something that will be run not very often, I'd just use iteration to keep things simple.

Select where HSTORE value is $value Laravel

Using the query builder to try and select rows where a value in the HSTORE key $type is present.
My Where Statement:
->where("meta_data_fields->'$type'", 'like', '%'.$query.'%')
Not sure what I'm doing wrong. I get this error:
Undefined column: 7 ERROR: column "meta_data_fields->'Entity::hstore'" does not exist
Any ideas?
to get all records in table that have HSTORE
Model::where("meta_data_fields", 'like', '%'.$query.'%')->get();
This should do normally do the trick. In your case, data in meta_data_fields is a json string. if the search is performed on all rows in the table, will select all. So here is What I did,
I created a queryScope in the model
1 - fetch all data
2 - extract meta_data_field and decode it
3 - loop through meta_data_field
4 - select only that match the criteria and build the array
here is a table
+----+-------------+------------------------------------+-----------+
| id | name | desc | vendor_id |
+----+-------------+------------------------------------+-----------+
| 1 | apples | {"type":"fruit","origin":"mexico"} | 1 |
| 2 | oranges | {"type":"fruit","origin":"peru"} | 1 |
| 3 | Peaches | {"type":"fruit","origin":"mexico"} | 2 |
| 4 | Cherries | {"type":"fruit","origin":"us"} | 1 |
| 5 | banans | {"type":"fruit","origin":"brazil"} | NULL |
| 6 | Water Melon | {"type":"fruit","origin":"mexico"} | 1 |
+----+-------------+------------------------------------+-----------+
public function scopeItems($name ="mexico"){
$items = array();
$data = Self::get();
$meta_fields = json_decode($data -> pluck('desc') ,true);
foreach ($meta_fields as $key => $value) {
if (isset($value['origin']) && $value['origin'] == $name ){
$items[$key] = $data[$key] -> toArray();
}
}
return $items;
}
// output
Array
(
[0] => Array
(
[id] => 1
[name] => apples
[desc] => Array
(
[type] => fruit
[origin] => mexico
)
[vendor_id] => 1
)
[2] => Array
(
[id] => 3
[name] => Peaches
[desc] => Array
(
[type] => fruit
[origin] => mexico
)
[vendor_id] => 2
)
[5] => Array
(
[id] => 6
[name] => Water Melon
[desc] => Array
(
[type] => fruit
[origin] => mexico
)
[vendor_id] => 1
)
)
Hope this works for you this time.
So here's what worked in my situation with Laravel.
$result = \DB::select(\DB::raw("SELECT hstore_fields, id from table where lower(hstore_fields->'$type') like lower('%$query%')"));

How to retrieve tree nodes children (recursive function help)

I have a binary, the database table of relationships looks like this:
+----+----------+---------+-----+
| id | parentID | childID | pos |
+----+----------+---------+-----+
| 1 | 1 | 2 | l |
| 2 | 1 | 3 | r |
| 3 | 2 | 4 | l |
| 4 | 3 | 5 | r |
| 5 | 4 | 6 | l |
| 6 | 5 | 7 | r |
+----+----------+---------+-----+
I am able to extract or children of for example 1 - but I have very clumsy function for that, so I need something that works better.
The output I need should look like this:
Array
(
[0] => Array
(
[id] => 2
[parentID] => 1
[pos] => l
)
[1] => Array
(
[id] => 4
[parentID] => 2
[pos] => l
)
[2] => Array
(
[id] => 6
[parentID] => 4
[pos] => l
)
[3] => Array
(
[id] => 3
[parentID] => 1
[pos] => r
)
[4] => Array
(
[id] => 5
[parentID] => 3
[pos] => r
)
[5] => Array
(
[id] => 7
[parentID] => 5
[pos] => r
)
)
So far I came up with this function, however it returns nested array, I want it flattened ... but whenever I tried it it just fails.
function children($pid) {
//set sql
$sql = "SELECT * FROM relationships WHERE parentID = ".$pid;
//save query to result
$result = mysql_query ($sql)
or die("Bad request " . mysql_error());
while ($item = mysql_fetch_array($result)):
$topchild["id"] = $item["childID"];
$topchild["parentID"]= $item["parentID"];
$topchild["pos"] = $item["pos"];
$children[] = $topchild;
$children[] = children($item["childID"]);
endwhile;
return $children;
}
What do I do wrong there?
I want it flattened
$children[] = children($item["childID"]);
instead add each of the items in the return value separately:
foreach (children($item['childID'] as $child)
$children[]= $child;
(Also shouldn't $topchild be initialised inside the loop?)
If you are doing a lot of recursive queries like this, a parent-child relation table is not a good choice of data structure. Consider one of the hierarchically-oriented solutions such as nested sets.

Categories