How to create PHP array from MySQL table - php

I have a MySQL table:
-------------------
|type_id|type_name|
-------------------
| 22 | Toyota |
| 22 | Mazda |
| 23 | Volvo |
| 23 | Man |
| 25 | Scania |
| 25 | Iveco |
| 25 | Fiat |
-------------------
which is created dynamically from user input. I want to create an array from the table using PHP like this:
array(
'22' => array('Toyota', 'Mazda'),
'23' => array('Volvo', 'Man'),
'25' => array('Scania', 'Iveco','Fiat'),
);
where array id will be type_id and elements will be type_name's of the type_id.I tried this:
$results = array();
while($line = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$results[] = $line;
}
print_r($results);
But I am getting:
Array (
[0] => Array (
[type_id] => 22
[type_name] => Toyota
)
[1] => Array (
[type_name] => 22
[type_name] => Mazda
)
...so on
Please help!

You need to change your code a bit and it will work fine:-
$results = array();
while($line = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$results[$line['type_id']][] = $line['Type_name']; //check change here
}
print_r($results);
Note:- check your column-names and correct them if any mistake is there.

Please replace your db name and table name in the code-
$conn = mysqli_connect("localhost","root","","dbname");
$query ="select * from table";
$exe = mysqli_query($conn,$query);
$input = array();
$type = array();
while ($result = mysqli_fetch_array($exe))
{
if(array_key_exists($result['type_id'], $input))
{
$type[] = $result['type_name'];
}
else
{
$type = array($result['type_name']);
}
$input[$result['type_id']] = $type;
}
echo "<pre>";
print_r($input);

select type_id and Type_name columns from table and in foreach loop do this:
$output = array();
foreach ($result as $item){
$output[$item['type_id']][] = $item['Type_name'];
}

Related

PHP: Adding multiple associative arrays to another array

Here's a sample of data
Date | Source | Amount
-----------------------
01A | S1 | 12
01A | S4 | 2
01A | S7 | 134
02A | S1 | 126
03A | S4 | 10
02A | S7 | 0
02A | S1 | 3
02A | S4 | 4
02A | S7 | 5
The resulting array needs to look like:
Array
(
[01A] => Array
(
[S1] => 12
[S4] => 2
[S7] => 134
)
[02A] => Array
(
[S1] => 126
[S4] => 10
[S7] => 0
)
[03A] => Array
(
[S1] => 3
[S4] => 4
[S7] => 5
)
)
I've tried looking at pages such as PHP Adding multiple associative arrays to new array based on key, PHP multiple arrays to one associative array and Merge multiple associative arrays to a single array of associative arrays and playing around with code as below (not using the same data - but same theory) but it's not producing what I need. The code below just shows A and B
$array = Array();
$a=array( "ABC" => array("A"=>"RED","B"=>"GREEN"));
$b=array( "ABC" => array("C"=>"BLUE","D"=>"YELLOW"));
$array = $a + $b;
echo '<pre>';
print_r($array);
echo '</pre>';
KISS
$result = array();
foreach($rows as $row)
{
if(!isset($result[$row['Date']])) $result[$row['Date']] = array();
$result[$row['Date']][$row['Source']] = $row['Amount'];
}
Assuming you already have the data in the $input array, the code is as easy as:
$result = array();
foreach ($input as $row) {
$date = $row['Date'];
if (! array_key_exists($date, $result)) {
$result[$date] = array();
}
$result[$date][$row['Source']] = $row['Amount'];
}
If you don't have the data in $input but you fetch it from the database just replace the line:
foreach ($input as $row) {
with something that matches your data retrieval loop, f.e.:
while ($row = mysqli_fetch_assoc($result)) {

Build Tree multidimensional array from database

How would I make an infinite recursion loop using php and mysql to build a specific array layout? I have writting out my tables, array layout and my attempt at getting this work. I have spent the last few hours working on this but am having no luck.
I am trying to build a php array based on my database that builds a specific layout when using json_encode
My Database tables look like the following
TABLE `info` | TABLE `relations`
+--------+-----------+ +--------+-----------+
| id | name + | id | parent_id |
+--------+-----------+ +--------+-----------+
| 2p03Me | sue | | b5ET7N | 2p03Me |
| b5ET7N | john | | h7S4bk | b5ET7N |
| h7S4bk | bob | | iMz4d7 | 2p03Me |
| iMz4d7 | sam | | ixRpaH | iMz4d7 |
| ixRpaH | teddy | | k41BhX | ixRpaH |
| k41BhX | dan | +--------+-----------+
+--------+-----------+
The generated array should look something like the following:
Array
(
[0] => stdClass Object
(
[text] => sue
[nodes] => Array
(
[0] => stdClass Object
(
[text] => john
[nodes] => Array
(
[0] => stdClass Object
(
[text] => bob
)
)
)
[1] => stdClass Object
(
[text] => teddy
[nodes] => Array
(
[0] => stdClass Object
(
[text] => dan
)
)
)
)
)
)
I have tried this a few times but I can't seem to get this to work. My latest and last attempt was
$tree = category_tree($mysqli, $origSnippet);
function category_tree($mysqli, $catid, $tree = array()) {
?><pre><?php print_r($tree); ?></pre><?php
$sql = "SELECT * FROM `relations` INNER JOIN `info` ON `relations`.`id`=`info`.`id` WHERE `relations`.`parent_snippet_id`='$catid'";
$children = $mysqli->query($sql);
while($child = $children->fetch_assoc()) {
$tree[] = array('text' => "$child[name]/$child[id]");
echo "$child[name]/$child[snippet_id]<br/>";
category_tree($mysqli, $child['id'], $tree);
}
return $tree;
}
Any help you may be able to provide would be very appricated.
## My Question ##
How would I make an infinite recursion loop using php and mysql to build a specific array layout? I have writting out my tables, array layout and my attempt at getting this work. I have spent the last few hours working on this but am having no luck.
I was able to resolve this problem by doing the following:
$tree = array();
$node_id = 0;
$origSnippet = "2p03Me"; //THIS IS GOTTEN FROM A SEPERATE FUNCTION BUT WILL BE THE STARTING POINT OF THE LOOP
function hasChildNodes($mysqli, $snippetID) {
$sql = "SELECT * FROM `relations` INNER JOIN `info` ON `relations`.`id`=`info`.`id` WHERE `relations`.`parent_id`='$snippetID'";
return $mysqli->query($sql)->num_rows;
}
function buildTree($mysqli, $snippetID, $node_id, &$tree) {
$sql = "SELECT * FROM `relations` INNER JOIN `info` ON `relations`.`id`=`info`.`id` WHERE `relations`.`parent_id`='$snippetID'";
$snippets = $mysqli->query($sql);
while($snippet = $snippets->fetch_assoc()) {
$tree[$node_id] = Array("text" => $snippet['name']);
if (hasChildNodes($mysqli, $snippet['id']) >= 1) {
buildTree($mysqli, $snippet['id'], 0, $tree[$node_id]['nodes']);
}
$node_id++;
}
}
$sql = "SELECT * FROM `info` WHERE `id`='$origSnippet' LIMIT 1";
$origSnippet = $mysqli->query($sql)->fetch_assoc();
$tree[$node_id] = Array("text" => $origSnippet['name']);
if (hasChildNodes($mysqli, $childSnippet) >= 1) {
buildTree($mysqli, $childSnippet, $node_id, $tree[$node_id]['nodes']);
}

mysqli result in array

i have this table produced from the query SELECT * FROM myTable
+--------------------------+---------+--------+
| Name | Version | Detail |
+--------------------------+---------+--------+
| name0 | 10 | xxx |
| name1 | 30 | yyy |
| name2 | 30 | zzz |
| name3 | 30 | kkk |
+--------------------------+---------+--------+
so, i need to have this table in a php array using mysqli function.
//$this->internalDB have the db connection
$result = $this->internalDB->query($query)->fetch_array(MYSQLI_NUM);
print_r($result);
produced
Array ( [Name] => name0 [Version] => 10 [Detail] => xxx )
cycles with the speech does not change ...
how i can do that?
This will query a database and return your values as an associative array in the $arrReturn variable.
$mysqli = new mysqli("host", "user", "password", "database");
$query = "SELECT * FROM myTable";
$sqlRes = $mysqli->query($query);
if (is_object($sqlRes)) {
$arrReturn = array();
while ($row = $sqlRes->fetch_assoc()) {
$arrRow = array();
foreach($row as $field => $value) {
$arrRow[$field] = $value;
}
$arrReturn[] = $arrRow;
}
echo $arrReturn[0]['Name']; // prints 'name0'
}
It might be helpful to read through the mysqli quickstart guide

Count inverse document frequency (idf) in every documents

I wanna count idf, the formula is IDF=log(D/df) that D is total data and df is many data that contain the searched words.
from the tables :
1. tb_stemming
===========================================================================
|stem_id | stem_before | stem_after | stem_freq | sentence_id |document_id|
===========================================================================
| 1 | Data | Data | 1 | 0 | 1 |
| 2 | Discuss | Discuss | 1 | 1 | 1 |
| 3 | Mining | Min | 1 | 0 | 2 |
===========================================================================
here's the code :
countIDF($total_sentence,$doc_id);
that $total_sentence is
Array ( [0] => 644 [1] => 79 [2] => 264 [3] => 441 [4] => 502 [5] => 18 [6] => 352 [7] => 219 [8] => 219 )
function countIDF($total_sentence, $doc_id) {
foreach ($total_sentence as $doc_id => $total_sentences){
$idf = 0;
$query1 = mysql_query("SELECT document_id, DISTINCT(stem_after) AS unique_token FROM tb_stemming group by stem_after where document_id='$doc_id' ' ");
while ($row = mysql_fetch_array($query)) {
$token = $row['unique_token'];
$doc_id = $row['document_id'];
$ndw = countNDW($token);
$idf = log($total_sentences / $ndw)+1;
$q = mysql_query("INSERT INTO tb_idf VALUES ('','$doc_id','$token','$ndw','$idf') ");
}
}
}
and the function of countNDW is :
function countNDW ($word) {
$query = mysql_query("SELECT stem_after, COUNT( DISTINCT sentence_id ) AS ndw FROM `tb_stemming` WHERE stem_after = '$word' GROUP BY stem_after");
while ($row = mysql_fetch_array($query)) {
$ndw = $row['ndw'];
}
return $ndw;
}
It can't worked well, especially in call from database. All I need is to count in every document_id. How to define it in my code ? please, help me.. thank you so much :)

Merge rows in the same id into array

I have sentence table :
======================================================================
| id_row | id_document | id_sentence | sentence |
======================================================================
| 1 | 1 | 0 | Example sentences A |
| 2 | 1 | 1 | Example sentences B |
| 3 | 2 | 0 | Example sentences C |
| 4 | 2 | 1 | Example sentences D |
======================================================================
I wanna merge sentence that have same id_document into array like => Array( [1] => Array ( [0] => Example sentences A [1] => Example sentences B ) [2] => Array ( [0] => Example sentences C [1] => Example sentences D ))
Here's the code :
<?php
require_once 'conf.php';
$sql = mysql_query('SELECT sentence FROM sentence group by id_document') or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
$sentence[] = $row['sentence'];
}
print_r($sentence);
?>
but, I just get one sentence in every different id_document. Help me. Thank you :)
Index the array on id_document, and add new entries to the array like this:
while ($row = mysql_fetch_array($sql)) {
$sentence[ $row['id_document'] ][] = $row['sentence'];
}
You can write:
while ($row = mysql_fetch_array($sql))
{
$sentence[$row['id_document']][] = $row['sentence'];
}
while ($row = mysql_fetch_array($sql))
$sentence[$row['id_document']][] = $row['sentence'];
Here's my final code :
<?php
require_once 'conf.php';
$sql = mysql_query('SELECT sentence, id_document FROM sentence ') or die(mysql_error());
while ($row = mysql_fetch_array($sql)) {
$sentence[$row['id_document']][] = $row['sentence'];
}
print_r($sentence);
?>

Categories