I'm trying to generate an array that will look like this:
Array ( [123 Smith St, Begora] => L1234 [55 Crumble Road, Mosmana] => L2456 [99 Jones Ave, Gestana] => L3456 )
which will ultimately be used for a select menu on an html form.
I'm retrieving a list of records and propertyID numbers from a database as follows:
foreach($records as $record) {
$propertyID = $record->getField('propertyID');
$property = $record->getField('propertyAddress');
echo $propertyID.'<br>';
echo $property.'<br>';
}
which displays like this when I retrieve 3 records:
L1234
123 Smith St, Begora
L2456
55 Crumble Road, Mosmana
L3456
99 Jones Ave, Gestana
I just can't work out how to convert this into an Array which I can then use later on in my page for generating a select menu.
Just do
foreach($records as $record) {
$propertyID = $record->getField('propertyID');
$property = $record->getField('propertyAddress');
$addresses[$property] = $propertyID;
}
Something like this:
$array = array();
foreach($records as $record) {
$array[$record->getField('propertyAddress')] = $record->getField('propertyID');
}
Related
I'm trying to modifiy some code I have that creates and array of objects for a menu from a database I need it to add the SubCategoryID to each item in the array
and for the life of me I'm having a mental blank on how to do it
<?php
include_once ('includes/sqlopen.php');
$sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName,
SubcategoryID
FROM products
GROUP BY SubcategoryID
ORDER BY CategoryName");
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
}
echo "Start of Array";
echo "<br>";
foreach ($menu['category'] as $cat) {
echo $cat."<br>";
foreach ($menu['SubcategoryName'][$cat] as $subcat) {
echo "--" . $subcat."<br>";
}
}
echo "<br>";
echo "End of Array";
include_once ('includes/sqlclose.php');
?>
Basically I want to achieve this:
Parent Cat 1 (link to prodlist.php?id=100)
--Child Cat1 (link to prodlist.php?id=103)
--Child Cat2 (link to prodlist.php?id=104)
Parent Cat 2 (link to prodlist.php?id=200)
Parent Cat 3 (link to prodlist.php?id=300)
--Child Cat1 (link to prodlist.php?id=301)
--Child Cat2 (link to prodlist.php?id=302)
and the database is layed out:
CategoryName SubcategoryName ItemName SubCategoryID
ParentCat1, ChildCat1, Item1, 103
ParentCat1, ChildCat1, Item2, 103
ParentCat1, ChildCat2, Item1, 104
ParentCat2, Item1, 200
ParentCat3, ChildCat1, Item1, 301
ParentCat3, ChildCat2, Item2, 302
** UPDATE- Thanks to everyone that is trying to help me, I know I'm probably not that great at explaining what I need help with..
I have been playing around with it for a little bit now and it is kind of doing what I want. I just have a small glitch where if 2 different parent categories have subcategories with the same name it will add both subcat ids to the array
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
$menu['SubcategoryID'][$row['SubcategoryName']][] = $row['SubcategoryID'];
}
Output
--Accessories
id--766
id--243
id--992
id--871
id--977
Monitor Arms
--Spacedec
id--789
--Visidec
id--791
--Telehook
id--792
--Spacepole
id--804
--Accessory
id--866
--Monitor Accessories
id--990
id--584
--Stands
id--991
id--538
First of all, you can improve your database structure
Like below:
id|category|parent_id
Simple and clean isn't.
Now try this:
//your database records
$rows = [
['id'=>1,'category'=>'Indland','parent_id'=>0],
['id'=>2,'category'=>'Udland','parent_id'=>0],
['id'=>3,'category'=>'Sport','parent_id'=>0],
['id'=>4,'category'=>'Handbold','parent_id'=>3],
['id'=>5,'category'=>'Fodbold','parent_id'=>3],
['id'=>6,'category'=>'Sample','parent_id'=>4]
];
print_r(getList($rows));
// Recursive function
function getList($rows, $id=0){
// Start a new list
$newList = null;
foreach($rows as $key => $row) {
if ($row['parent_id'] == $id) {
// Add an UL tag when LI exists
$newList == null ? $newList = "<ul>" : $newList;
$newList .= "<li>";
$newList .= "{$row['category']}";
// Find childrens
$newList .= getList(array_slice($rows,$key),$row['id']);
$newList .= "</li>";
}
}
// Add an UL end tag
strlen($newList) > 0 ? $newList .= "</ul>" : $newList;
return $newList;
}
This will result in:
The DB structure is the obvious issue here as it's using a fixed structure. While this could be efficient in certain scenarios it's not easily extensible. A way to achieve what you are currently trying to achieve will be this:
Fetch and group all items (in code) by CategoryName (I'm hoping the category name is a slug?)
For each category name, display all subcategories with link to id
Translated to code this will be something like this (Your current SQL query is fine):
$menu = [];
while ($row = mysqli_fetch_assoc($sql)) {
if (!isset($menu[$row['CategoryName']])) {
$menu[] = $row['CategoryName'];
}
if (!empty($row['SubCategoryName']))
$menu[$row['CategoryName']][] = $row['SubcategoryName'];
}
}
echo "Start of Array";
echo "<br>";
foreach ($menu as $cat => $catsubs) {
echo $cat."<br>";
foreach ($catsubs as $sub) {
echo "--" . $sub."<br>";
}
}
echo "<br>";
echo "End of Array";
ok guys I think I have it.. ill post it up so that on the rare chance anyone else can benefit from it.. Thanks again to everyone that helped me
Code
<?php
include_once ('includes/sqlopen.php');
$sql = mysqli_query($conn, "SELECT CategoryName, SubcategoryName, CategoryCode, SubcategoryID
FROM products GROUP BY SubcategoryID ORDER BY CategoryName");
$menu = array();
while ($row = mysqli_fetch_assoc($sql)) {
// Creates First Level Array Items For Parent IDs
if (!in_array($row['CategoryName'], $menu['category'])) {
$menu['category'][] = $row['CategoryName'];
}
if (!empty($row['SubcategoryName']))
// Creates Second Level Array for Child IDs
$menu['SubcategoryName'][$row['CategoryName']][] = $row['SubcategoryName'];
// Creates Third Level Array for Category IDs
$menu['SubcategoryID'][$row['SubcategoryName']][$row['CategoryName']][] = $row['SubcategoryID'];
}
echo "Start of Array";
echo "<br>";
foreach ($menu['category'] as $cat) {
echo $cat."<br>";
foreach ($menu['SubcategoryName'][$cat] as $subcat) {
echo "--" . $subcat."<br>";
foreach($menu['SubcategoryID'][$subcat][$cat] as $id)
echo "id--".$id."<br>";
} echo "<br>";
}
echo "<br>";
echo "End of Array";
include_once ('includes/sqlclose.php');
?>
<pre>
<?php print_r ($menu); ?>
</pre>
Foreach Loop Output
CPU
--AMD Socket FM2
id--778
--Mobile
id--558
--Intel Socket 1150 (4th Gen)
id--825
--Intel Socket 1151 (6th Gen Skylake)
id--945
--AMD Socket AM3
id--693
--Intel Xeon
id--980
--Intel Socket 2011 (3rd and 4th Gen)
id--744
--Intel Socket 1151 (7th Gen Kabylake)
id--1021
--AMD Socket AM4
id--1023
print_r Output
[AMD Socket FM2] => Array
(
[CPU] => Array
(
[0] => 778
)
)
[Mobile] => Array
(
[CPU] => Array
(
[0] => 558
)
)
[Intel Socket 1150 (4th Gen)] => Array
(
[CPU] => Array
(
[0] => 825
)
)
[Intel Socket 1151 (6th Gen Skylake)] => Array
(
[CPU] => Array
(
[0] => 945
)
)
[AMD Socket AM3] => Array
(
[CPU] => Array
(
[0] => 693
)
)
[Intel Xeon] => Array
(
[CPU] => Array
(
[0] => 980
)
)
[Intel Socket 2011 (3rd and 4th Gen)] => Array
(
[CPU] => Array
(
[0] => 744
)
)
I'm trying to put values into name arrays from a table and array entries are over-riding each other
Code:
$list = array();
$name = db_query("SELECT name FROM {name_list}");
while ($num = db_fetch_array($name)){
$list[$num['name']]=array('title'=>$num['name']);
}
$values = db_query("SELECT id,name1,name2 FROM {status}");
while ($val = db_fetch_array($values)){
$list[$val['name1']] = array($val['id'] =>$val['id']);
$list[$val['name2']] = array($val['id'] =>$val['id']);
}
$output .= dprint_r($list);
The first while loop writes the titles of each array which are the names from the name db table.
The table:
name
Alice
Kate
Jason
John
Sam
the second while loop goes into the status table which looks something like:
id name1 name2
1 Alice Kate
2 Jason Kate
3 Kate Alice
4 Jason John
The final arrays should look something like:
Alice array (
1,3);
Jason array (
2,4);
Kate array (
1,2,3);
Sam array (
); etc...
Instead its looking like alice (3) Jason(4) Kate(3) etc...
Although I have no drupal for testing the error seems clear. Use the [] operator to push elements to the end of the id-per-name array. Try :
$list = array();
$name = db_query("SELECT name FROM {name_list}");
while ($num = db_fetch_array($name)){
$list[$num['name']]=array(); // initialize as empty array. you won't need the name
// twice as its already the index to $list
}
$values = db_query("SELECT id,name1,name2 FROM {status}");
while ($val = db_fetch_array($values)){
$list[$val['name1']][] = $val['id']; // add id to the first name's list
$list[$val['name2']][] = $val['id']; // add id to the second name's list
}
I'd like to SELECT rows from a database table and group them using PHP instead of SQL based on a parameter (in this case by item).
SQL:
Clothes table
id item owner
1 shoes joe
2 pants joe
3 hat joe
4 pants joe
5 hat tom
SELECT * from Clothes where owner='joe'
1 shoes joe
2 pants joe
3 hat joe
4 pants joe
Here's how I'd like the results to look after using PHP instead of SQL's GROUP BY item
PHP :
1 shoes joe
2 pants joe //count 2
3 hat joe
I'm sure there is a PHP array function for this I'm just not familiar, thoughts?
The easiest way is to exploit the uniqueness of array keys:
$grouped = array();
while ($row = $db->fetchResult()) { // or however you get your data
if (isset($grouped[$row['item']])) {
$grouped[$row['item']]['count']++;
} else {
$grouped[$row['item']] = $row + array('count' => 1);
}
}
Using pseucode for the database access functions, I believe this should work:
$sql = "SELECT * from Clothes where owner='joe'";
$res = query($sql);
$arr = array();
while ($row = $res->fetch())
{
$arr[] = $row['item'];
}
$arr = array_unique($arr);
You should note that this might give you a "sparse array" (in other words, there may be gaps in the keys). And as said in the comments, it's usually better to do this in SQL if you have that option. Even if that means executing two similar queries.
function group($items, $field) {
$return = array();
foreach ($items as $item) {
$key = $item[$field];
if (isset($return[$key])) {
$return[$key]['count']++;
} else {
$return[$key] = $item;
$return[$key]['count'] = 1;
}
}
return $return;
}
print_r(group($results, "item"));
I am having an issue with updating records from an array. When I go to update I am only getting the first digit. For example if the real value is 58 I am only getting the 5 inserted
Below is my code with further explanation below:
$bidArr = $tmpArr;
foreach($tmpArr as $key => $val)
{
$sqlEp = "select sum(endpoints_c), account_id1_c as id from accounts_cstm as ac join accounts as a on a.id = ac.id_c
where account_id1_c ='$val' and (status_c IN ('active','llp')) and deleted='0'";
$rowEp = $db->query($sqlEp);
$recordEp = $db->fetch_row($rowEp);
$bidArr[$key]['sold_ep_c'] = $recordEp[0];
//print "<pre>EP";
//print_r($recordEp);
}
foreach($bidArr as $key => $val)
{
$data['sold_ep_c'] = $val['sold_ep_c'];
$db->query_update(TABLE_ACC, $data, "id_c='".$key."'");
print "<pre>EP";
print_r($key);
print_r($data);
}
What is happening is when I uncomment the first print_r I get:
EPArray
(
[0] => 16
[1] => 51067d38
which is right. But if I comment it out and uncomment the second one I get:
51067d38
(
[sold_ep_c] => 1
)
Why is this stripping the first digit?
As per chat...your arrays aren't initialized.
$bidArr[$key] = array(); in the first loop!
I have a database that stores accounts and subscriptions. An account can contain accounts and subscriptions and have more than three parent levels.
A row from the database query result looks something like this:
$array = (0 => array("level" => "2", "accountno" => "123124234", "accountname" => "Hansel", "parentaccountno" => "000213123", "subscription" => "5423213213", "username" => "Gretchen");
(Level 1 means that it is top level and it will have PARENTACCOUNTNO = null).
From this I am trying to create a multidimensional array which looks something like this:
accounts:
000213123
accounts:
123124234
name: Hansel
subscriptions:
5423213213
username: Gretchen
This is the code I have so far, which works really well on the first two levels. When there are are three levels or more things become more complicated, since each account only knows about its own parent:
$hierarchy = array();
foreach ($decode as $row) {
$accountno = $row["ACCOUNTNO"];
$msisdn = $row["MSISDN"];
if ($row["PARENTACCOUNTNO"] == null)
$base_array_key = $hierarchy["accounts"];
$base_array_key[$accountno] = array("name" => $row["ACCOUNTNAME"], "accounts" => array(), "subscriptions" => array());
$hierarchy["accounts"][$accountno]["accounts"]["321323123213"] = "blaha";
if ($row["MSISDN"] != null)
$hierarchy["accounts"][$accountno]["subscriptions"][$msisdn] = array("enduser" => $row["ENDUSER"]);
}
The solution I have in mind right now is to pass the base key from each iteration to the next iteration, and then if for example the previous level was two levels above this one just use some sort of string replace to remove the last two parts of the key.
Any better ideas? I am quite sure this is a shitty way of doing what I am trying to accomplish.
Do all your results look like that ? So then, where's are the parent accounts ? Or am i missing something ? I would simple rewrite the query to get a more "linear" result, like:
parentaccountno | accountno | accountname | bla
-----------------------------------------------
000213123 | 123124234 | Hansel | abc
When every result row looks like this, you can simple create your final array like that:
foreach ($decode as $row) {
$my_array = [ $row["parentaccountno"] ][ $row["accountno"] ]["accountname"] = $row["accountname"];
$my_array = [ $row["parentaccountno"] ][ $row["accountno"] ]["bla"] = $row["bla"];
}
Create a temporary associative array:
$all_records = array();
Populate it with the results you find in the database:
while($result = get_results_from_db()) {
$accountno = $result[accountno];
$all_records[$accountno] = $result;
}
Now you have an array indexed by account numbers so it's easy to find any record if you know it's account number. So you iterate through the array to associate children to parents:
$top_level_records = array();
foreach($all_records AS $record) {
$parentaccountno = $record[parentaccountno];
if(!empty($parentaccountno)) {
$parent = &$all_records[$record[parentaccountno]];
if(empty($parent['accounts']))
$parent['accounts'] = array()
$parent['accounts'][] = $record;
}
else {
$top_level_records[] = $record;
}
}
I appreciate the answers, but I think the problem is my database query which should contain records of all the parents of an account and not just the parent, using something like SYS_CONNECT_BY_PATH in Oracle SQL.