I am trying to get values from MySQL array as alphabetically, and I want results like:
[B] => Array (
[id] => 6
[firstname] => Bon
[lastname] => Jone
),
Array (
[id] => 7
[firstname] => bon
[lastname] => doe
)
[H] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
[J] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
Here is the code of what I have tried.
edited
$result = mysqli_query($GLOBALS['conx'],"SELECT * FROM $users_table ORDER BY firstname ASC");
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$row['alphabets'] = ucfirst($firstname[0]);
$data[] = $row;
}
But it outputs like this:
[0] => Array
(
[id] => 6
[firstname] => Bon
[lastname] => Jone
)
[1] => Array
(
[id] => 7
[firstname] => bon
[lastname] => doe
)
[2] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
[3] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
How can I get output like this:
A
Adam Smith
Alan smith
B
Bone Doe
Bone Joe
J
John Smith
.... etc
ucfirst returns the entire string with the first letter capitalised, you'll need to grab just the first letter with substr first.
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$key = strtoupper($firstname[0]))
$data[$key][] = $row;
}
To get the output (roughly) like you want, try something like:
foreach ($data as $letter => $rows)
{
echo "<h1>{$letter}</h1>", PHP_EOL;
foreach ($rows as $row)
{
echo "<p>{$row['firstname']} {$row['lastname']}</p>", PHP_EOL;
}
}
Your attempt will not do what you want. To achieve this, you will have to create a nested array, then on each iteration check the first letter of the firstname. Check if that letter already exists as a key in the array, and create an item in your array with an empty array as its value, it if it doesn't, and then add the row data to it to that newly created empty array.
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
$firstLetter = strtoupper($row["firstname"][0]); // convert to upper case so all are the same
if (array_key_exists($firstLetter, $data) === false) $data[$firstLetter] = [];
// now just add the row data:
$data[$firstLetter][] = $row;
}
First use Order in your MySQL Query: ... ORDER BY firstname ASC
Create Arrays for Alphabets using PHP:
$Alphabetic_Array = array();
while ($row = mysqli_fetch_assoc($result)) {
$Alphabetic_Array[$row['firstname'][0]][] = $row;
}
First of all, I suggest you to sort records in your query, otherwise you have to sort resulting array before grouping it:
SELECT * from tablename
ORDER BY firstname ASC, lastname ASC
Then, you can use array_map to group your array:
$result = array();
array_map
(
function( $row ) use( &$result )
{
$result[strtoupper(substr($row['firstname'],0,1))][] = $row;
},
$data
);
(Note that we have to call $result by reference)
Now the $result is an array like this:
Array
(
[B] => Array
(
[0] => Array
(
[id] => 7
[firstname] => bon
[lastname] => doe
)
[1] => Array
(
[id] => 6
[firstname] => Bon
[lastname] => Jone
)
)
[H] => Array
(
[0] => Array
(
[id] => 1
[firstname] => Hassan
[lastname] => Ilyas
)
)
[J] => Array
(
[0] => Array
(
[id] => 5
[firstname] => John
[lastname] => Doe
)
)
)
If you want/can use PDO instead of mysqli_, you can obtain desired result directly from MySQL query. Set your query in this way:
SELECT UPPER(SUBSTR(firstname,1,1)) as initial, tablename.* from tablename
ORDER BY firstname ASC, lastname ASC
and then, fetching in in this way:
$data->fetchAll( PDO::FETCH_ASSOC|PDO::FETCH_GROUP );
your $data will contain desired array, without need of additional processing.
The PDO::FETCH_GROUP option groups fetched results by first column returned by query, in your case the capitalized firstname first letter.
What about letting MYSQL do the logic?
SELECT * FROM users_table, SUBSTRING(firstName, 1, 1) as initial ORDER BY firstname ASC
Then you just can append each line to an array
while ($row = mysqli_fetch_assoc($result)) {
$Alphabetic_Array[$row['initial'] = $row;
}
It's just pseudo code but I think the idea is pretty clear
Related
I have this existing array
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
)
)
I want to insert new item in each array like [randomNumber] => 50. So the final output must be like this
Array
(
[0] => stdClass Object
(
[userid] => 1
[user] => John Doe
[randomNumber] => 25
)
[1] => stdClass Object
(
[userid] => 2
[user] => Mae Smith
[randomNumber] => 50
)
)
I'm using php using for loop to insert the randomNumber every user
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i] = array('randomNumber' => rand(10,100));
}
It doesn't seems to work. What should be the proper way? Thanks
Iterate with a foreach, and as $user is an object, it will be passed to loop by reference:
foreach ($users as $user) {
$user->randomNumber = rand(10,100);
}
As you have an array of objects rather than arrays...
for($i=0 ; $i<count($users) ; $i++) {
// insert randomNumber here
$users[$i]->randomNumber = rand(10,100);
}
I think foreach function is better for you. and you have array of objects.
foreach ($users as $key => $value) {
$users[$key]->randomNumber = rand(10,100);
}
I am trying to fetch one array from an Oracle database and another from a MySQL database.
But the arrays I get back are in different formats, and I am not able to display them in an HTML table.
$result = $instance->prepare("SELECT * from dd ");
$result->execute();
while ($row = $result->fetchAll(PDO::FETCH_ASSOC))
{
$rows2 = $row;
}
$array = oci_parse($conn, "SELECT * FROM DD");
oci_execute($array);
while($row=oci_fetch_array($array, OCI_ASSOC))
{
$rows1 =$row;
}
print_r($rows1);
print_r($rows2);
$output = array_merge($rows1,$rows2);
print_r($output);
Here $instance and $conn are the respective connection variables.
The outputs I get after printing the two arrays are:
Array from Oracle:
Array ( [CLIENTID] => 2 [CLIENTNAME] => dsd [PHONENO] => 53556535 [ADDRESS] => Mumbai [ROUTE] => 4323 )
Array from MySQL:
Array ( [0] => Array ( [ClientId] => 3 [ClientName] => PQR [PhoneNo] => 786483744 [Address] => Pune [Route] => 3329 ) )
And after merging I get this array:
Array ( [CLIENTID] => 2 [CLIENTNAME] => dsd [PHONENO] => 53556535 [ADDRESS] => Mumbai [ROUTE] => 4323 [0] => Array ( [ClientId] => 3 [ClientName] => PQR [PhoneNo] => 786483744 [Address] => Pune [Route] => 3329 ) )
How do I print this in a table in HTML format?
You can not just merge two arrays in this case.try code below;
$all = array();
$all[] = $rows1;
foreach($rows2 as $k2=>$v2) {
$new=array();
$new['CLIENTID'] = $v2['ClientId'];
$new['CLIENTNAME'] = $v2['ClientName'];
$new['PHONENO'] = $v2['PhoneNo'];
$new['ADDRESS'] = $v2['Address'];
$new['ROUTE'] = $v2['Route'];
$all[]=$new;
}
$str='<table><tr><th>CLIENTID</th><th>CLIENTNAME</th><th>PHONENO</th><th>ADDRESS</th><th>ROUTE</th></tr>';
foreach($all as $arr) {
$str.='<tr><td>'.$arr['CLIENTID'].'</td><td>'.$arr['CLIENTNAME'].'</td><td>'.$arr['PHONENO'].'</td><td>'.$arr['ADDRESS'].'</td><td>'.$arr['ROUTE'].'</td>';
}
$str.='</table>';
echo $str;
If $rows1 is an array-array like $rows2, you should iterate same loop for $rows1 also
This is probably a stupidly easy question, but I'm suffering from brainfade ... I'm using a SELECT statement to pull data from a MySQL Database then looping through it with a WHILE loop to push the returned data to the array '$arr', using the code below;
$query="SELECT idBaptism as id, baptismDate as eventDate, concat(baptismForename,' ',baptismSurname) as name, churchName, tbLocation.idLocation as locationid, location, clat as lat, clng as lng FROM tbBaptism, tbLocation, tbChurch WHERE tbBaptism.idLocation=tbLocation.idLocation AND tbBaptism.idChurch=tbChurch.idChurch";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row;
}
}
My question is I want to append the text 'Baptism' onto the end of each row of the array, what's the easiest way to do this??
As an example, here is the sample output of two rows of the array produced from the code above using print_r;
Array ( [0] => Array ( [id] => 1 [eventDate] => 1874-03-08 [name] => Henry Stanley [churchName] => St. Leonards [locationid] => 28 [location] => Halwell, Devon, UK [lat] => 50.366001 [lng] => -3.720500 )
[1] => Array ( [id] => 2 [eventDate] => 1870-11-06 [name] => Valentine Joles [churchName] => St. John The Evangelist [locationid] => 27 [location] => East Horrington, Somerset, UK [lat] => 51.218143 [lng] => -2.600683 )
I want to add value pair on the end of each row, such as [type] => 'Baptism' ...
Simply push the new element to the fetched array $row and then push it to the array $arr, like this:
// your code
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$row['type'] = 'Baptism';
$arr[] = $row;
}
}
I have a php /mysqli query and I want to populate an array with the results:
$query3 ="SELECT * FROM conditions";
$results = array();
if ($result = mysqli_query($conn, $query3)){
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
print_r($results);
Something is wrong here -its making arrays within arrays I think. (to be honest I am confused by this result)
How do I do this correctly!
Array (
[0] => Array ( [condition_id] => 1 [condition_name] => Epilepsy )
[1] => Array ( [condition_id] => 2 [condition_name] => ASD )
[2] => Array ( [condition_id] => 3 [condition_name] => BESD )
[3] => Array ( [condition_id] => 4 [condition_name] => HI )
[4] => Array ( [condition_id] => 5 [condition_name] => Medical )
[5] => Array ( ...
Thanks for all the help - now how should I create what I actually want which is one array with key=>value like this:
array (1=>epilepsy, 2=>ASd...) - the numbers refer to the primary key.
How do I populate an array from this query please?
Change your code as below :
while($row = mysqli_fetch_assoc($result))
{
$results[$row['condition_id']] = $row['condition_name'];
}
Move to PDO, Luke.
$results = $pdo->query("SELECT FROM conditions")->fetchAll(PDO::FETCH_KEY_PAIR);
print_r($results);
Whoops! Is that all the code?
I'm retrieving some data from a database where the values might be something like the following:
Column1 | Column2
-----------------
Bob | 24
Joe | 17
Jimmy | 38
Joe | 10
Bob | 5
Sam | 8
With this data, I want to somehow select the Bob rows and multiply them together. I want to do this for all rows that match in Column1. I'm not concerned about doing it in SQLite, but what is the best way to go about this in PHP? I've currently added the results to an array in PHP by doing the following:
$myArray[$resultRow['Column1']] = $resultRow['Column2'];
I was wondering how to go about navigating through this and finding matching keys, multipying their values together, and outputting something like
Column1 = Column2-a * Column2-b
consider this code:
$results = array();
foreach(array('Bob' => 24, 'Joe' => 17, 'Jimmy' => 38, 'Joe' => 10, 'Bob' => 5, 'Sam' => 8) as $key => $val){
$results[$key][] = $val;
}
echo '<pre>';
print_r($results);
echo '</pre>';
out put:
Array
(
[Bob] => Array
(
[0] => 5
)
[Joe] => Array
(
[0] => 10
)
[Jimmy] => Array
(
[0] => 38
)
[Sam] => Array
(
[0] => 8
)
)
PHP ignores duplicate key, you have to create $results array when you retreiving the data from database, lets assume that you do like this:
while () {
$col1 = $row["col1"];
$col2 = $row["col2"];
$results[$col1][] = $row["col2"];
}
now the results array must be like this:
Array
(
[Bob] => Array
(
[0] => 24
[1] => 5
)
[Joe] => Array
(
[0] => 17
[1] => 10
)
[Jimmy] => Array
(
[0] => 38
)
[Sam] => Array
(
[0] => 8
)
)
now, its easy to search for colmun1 names like this:
$values_for_colmn1 = $results[$column1]; //which is an array
// use array_product() function for array product
$product_for_column1 = array_product($values_for_colmn1);
First, to read only Bob's values:
$stmt = $db->prepare('SELECT Column2 FROM MyTable WHERE Column1 = ?')
$stmt->bindValue(1, 'Bob', SQLITE3_TEXT);
$result = $stmt->execute();
Then, multiply all of them:
$value = 1.0;
while ($res = $result->fetchArray()) {
$value = $value * $res['Column2'];
}