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
}
Related
Apologies if posted already.
Struggling with array_merge function.
It works fine when we use it like this.
array_merge($array1,$array2);
In my case both arrays are from MySQL result.
See the following code for understanding it better.
$getfilelist = 'select * from fileartist fid IN (210,209)'; // fetching two rows
$FILE = $db->query($getfilelist);
$file_tot = count($FILE);
for($i=0;$i<$file_tot;$i++)
{
$artist = explode(',', $FILE[$i]['artist']); // Because Artist names saved like this `A,B` in first row and `A,C,D` in second.
}
print_r($artist);
This prints something like this.
Array // artist in first row
(
array[0] => A
array[1] => B
)
Array // artist in second row
(
array[0] => A
array[1] => C
array[2] => D
)
I want array should -
Array
(
array[0] => A
array[1] => B
array[2] => C
array[3] => D
)
I tried following code.
$getfilelist = 'select * from fileartist fid IN (210,209)'; // fetching two rows
$FILE = $db->query($getfilelist);
$file_tot = count($FILE);
for($i=0;$i<$file_tot;$i++)
{
$artist = explode(',', $FILE[$i]['artist']); // Because Artist names saved like this `A,B` in first row and `A,B,C` in second.
$merged = array_merge($artist);
$unique = array_unique($merged);
}
print_r($unique);
Results is
Array
(
array[0] => A
array[1] => B
)
Array
(
array[0] => A
array[1] => C
array[2] => D
)
This is not expected result.
In above code, I need something like this -> array_merge($FILE[0], $FILE[1]); for get expected result. Can't figure out how to code it.
I know array_merge function require two or more array but can't figure out how give both array to array_merge function.
Suggest me how to print only A,B,C,D in above case. Is I'm missing something? Or this is bad coded script?
Also, can this post may have more better title for future users.
try this
$getfilelist = 'select * from fileartist fid IN (210,209)'; // fetching two rows
$FILE = $db->query($getfilelist);
$file_tot = count($FILE);
$artist=[];
for($i=0;$i<$file_tot;$i++)
{
$artist = array_merge($artist,explode(',', $FILE[$i]['artist'])); // Because Artist names saved like this `A,B` in first row and `A,C,D` in second.
}
print_r(array_unique($artist));
or
$getfilelist = 'select * from fileartist fid IN (210,209)'; // fetching two rows
if($result = $mysqli->query($getfilelist)){
$artist=[];
while($FILE = $result->fetch_assoc()){
array_merge($artist,explode(',', $FILE['artist']));
}
}
print_r(array_unique($artist));
This will works for an Album's full info.
I posted it here for future user.
$getfilelist = 'select * from fileartist fid IN (210,209)'; // fetching two rows
$FILE = $db->query($getfilelist);
$file_tot = count($FILE);
$artist=[];
$music=[];
$label=[];
$lyrics=[];
for($i=0;$i<$file_tot;$i++) {
$artist = array_merge($artist,explode(',', $FILE[$i]['artist'])); // Because Artist names saved like this `A,B` in first row and `A,C,D` in second.
$music = array_merge($music,explode(',', $FILE[$i]['music']));
$label = array_merge($label,explode(',', $FILE[$i]['label']));
$lyrics = array_merge($lyrics,explode(',', $FILE[$i]['lyrics']));
}
print_r(array_unique($artist));
print_r(array_unique($music));
print_r(array_unique($label));
print_r(array_unique($lyrics));
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');
}
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"));
ok, a bit of background,
just into codeigniter
not a fan of sql and server-side scripts
i know what joins are
i have a many-to-many database for the first time
it's because joins typically have the following example as a result. but i wanted to parse this without having to build code to ignore repetitions. it's a 3-table join sample. the issue of repeating values increases as i join more tables:
table1.authorid table1.authorname table2.books table3.favorited
1 john john's book 1 jean
1 john john's book 1 joe
1 john john's book 2 ken
1 john john's book 2 mark
2 mark mark's book 1 alice
2 mark mark's book 1 ted
2 mark mark's book 2 sarah
2 mark mark's book 2 denise
is there a way in codeigniter (or plain PHP) that i can get this array form and turn it into something like json (and parse it like json)
$result = [
{
'authorid':1,
'authorname':'john',
'books':['john's book1','john's book2'],
'favorited':['jean','joe','ken','mark']
},
{
'authorid':2,
'authorname':'mark',
'books':['mark's book1','mark's book2'],
'favorited':['alice','ted','sarah','denise']
}
]
Update: this is not limited to this depth of objects/arrays (like in the example). it can go deeper (arrays in arrays, arrays in objects, objects in arrays, objects in objects)
// first, we need the SQL results in the $result_array variable
$sql = 'SELECT ...'; // your SQL command
$result_array = $this->db->query($sql)->result_array(); // codeigniter code
// here the real answer begins
$result = array();
foreach ($result_array as $row)
{
if (!isset($result[$row['authorid']])
{
$author = new StdClass();
$author->authorid = $row['authorid'];
$author->authorname = $row['authorname'];
$author->books = array($row['books']);
$author->favorited = array($row['favorited']);
$result[$row['authorid']] = $author;
}
else
{
if (!in_array($row['books'], $result[$row['authorid']]->books))
{
$result[$row['authorid']]->books[] = $row['books'];
}
if (!in_array($row['favorited'], $result[$row['authorid']]->favorited))
{
$result[$row['authorid']]->favorited[] = $row['favorited'];
}
}
}
$result = array_values($result);
echo json_encode($result);
I am going to select a list of items from a table, and pass it using json-framework.
Example, I want to select friends from my "shirts" table, from "players_shirts" table
pid | sid
================
1 | 2
2 | 3
1 | 5
Lets say, I get 30++ result (rows).
I assume (not yet tested this code), in php, I assign it by:
$array;
$count = 0;
while($r = mysql_fetch_assoc($exe){
$array[$count] = $r['sid'];
// EDIT START: I forgot to add counter
$count++;
// EDIT END
}
echo json_encode($array)
Is this method efficient/good enough?
I am new to php/database/manipulating data from database.
There is no need to specify an array keys in your case, so your code could be rewritten as:
$array = array();
while($r = mysql_fetch_assoc($exe){
$array[] = $r['sid'];
// or you may use array_push($array, $r['sid']); instead of the line above.
}