I have a problem…
I am trying to create an array from a mysql table.
But I don’t know how to format the data coming out of MySQL into an array in php.
Here is what I have done so far...
//Generate Org Data
$result_org = mysql_query("SELECT emp_no,sup_empno,Name,Title FROM employees");
// Initializes a container array
$orgArray = array();
while($row = mysql_fetch_array($result_org, MYSQL_ASSOC))
{
$currempno = $row['emp_no'];
$currsupervisor = $row['sup_empno'];
$currtitle = $row['Name']. '\n ' .$row['Title'];
// This is where I haven't a clue to get it the right format...??
// Stores each database record to an array
$buildorg = array("$currempno","$currsupervisor","$currtitle");
// Adds each array into the container array
array_push($orgArray, $buildorg);
}
// show the data to verify
echo ($orgArray);
// the data needs to be exactly like this below
o.addNode(003, 002, '', 'Jane Doe\nAsst Manager');
where 003 is the $currempno 002 is the $currsupervisor Jane Doe\nAsst
Manager is $currtitle
getting the o.addNode( along with the commas and double quotes and ending );
around this has me perplexed
Any help would be appreciated…
K Driscoll
If I understand correctly, you are actually trying to create line
o.addNode(003, 002, '', 'Jane Doe\nAsst Manager');
so just put the values into the string and format it the way you want to - there is no need to create another array - you can create final strings and push those into the array:
$currempno = $row['emp_no'];
$currsupervisor = $row['sup_empno'];
$currtitle = $row['Name']. '\n ' .$row['Title'];
$output = sprintf("o.addNode(%03d, %03d, '', '%s');", $currempno, $currsupervisor, $currtitle);
array_push($orgArray, $output);
I guess this is what you are look for, more or less:
$finalArray = array();
$result_org = mysql_query("SELECT emp_no,sup_empno,Name,Title FROM employees");
while( $row = mysql_fetch_array($result_org, MYSQL_ASSOC) ) {
$finalArray[] = array(
$row['emp_no'],
$row['sup_empno'],
$row['Name'].'\n'.$row['Title']
);
}
print_r($finalArray);
You used array_push function, better use another construction: $someArray[] = $newElement; — it has to do same. Example below.
This code will work:
//Generate Org Data
$result_org = mysql_query("SELECT emp_no,sup_empno,Name,Title FROM employees");
// Initializes a container array
$orgArray = array();
while($row = mysql_fetch_array($result_org, MYSQL_ASSOC))
{
$currempno = $row['emp_no'];
$currsupervisor = $row['sup_empno'];
$currtitle = $row['Name']. '\n ' .$row['Title'];
$orgArray[] = array($currempno, $currsupervisor, $currtitle);
}
var_dump($orgArray);
Related
I have a PHP code which has the following output:
[{"stockdata":29655.88482666}]
And I need to change the code on my php to get the result in this format:
[{"data": [29655.88482666]}]
This is the code of my php:
<?php
function getArraySQL(){
$startd = "29964";
$endd = "29968";
$dsn = "prueba";
$connect = odbc_connect( $dsn, '', '' );
$query = "
Select SUM(TON_DESCARGADO) as stockdata
from
(Select unit,[load],enum_LOAD.[name],SUM(dumptons) as TON_DESCARGADO
from hist_dumps inner join hist_loclist on hist_dumps.shiftindex = hist_loclist.shiftindex
and hist_dumps.loc = hist_loclist.locid
inner join enum_LOAD on hist_dumps.[load] = enum_LOAD.[num]
where hist_dumps.shiftindex between '$startd' and '$endd'
GROUP BY loc,UNIT,unit#,[load],enum_LOAD.[name])TEMP1
where unit = 'Stockpile'
GROUP BY unit
order BY UNIT";
if(!$rs = odbc_exec($connect, $query)) die();
$rawdata = array();
$i=0;
while($row = odbc_fetch_array($rs))
{
$rawdata[$i] = $row;
$i++;
}
odbc_close( $connect );
return $rawdata;
};
$stockdata = getArraySQL();
echo json_encode(($stockdata), JSON_NUMERIC_CHECK);
What need to be changed to get the correct format? Should I do something to improve the code of my php?
How should I write it if I connect php to SQL server via PDO and get the same result? (just an optional doubt)
I don't find custom output in json_encode, so if you want to customize the output of array , you would need to prepare it.
I assumed the data exists at zero index (0).
So, I use $stockdata[0]
for JSON_NUMERIC_CHECK replace, used (float)
here is the preparation of output to send exactly you want.
$stockdata = getArraySQL();
$Numeric_data = (float) $stockdata[0];
$data = '[{"data": ['.$Numeric_data.']}]';
echo $data;
Demo
I wrote an import snippet to populate my Neo4J DB with nodes for towns and related to them counties. The code looks like
<?php
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
$lineCount=0;
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024, ';', '"');
$lineCount++;
}
fclose($file_handle);
return array($line_of_text,$lineCount);
}
// Create an Index for Town and for Country
$queryString = '
CREATE INDEX ON :Country (name)
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString);
$result = $query->getResultSet();
$queryString = '
CREATE INDEX ON :Town (name)
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString);
$result = $query->getResultSet();
// Set path to CSV file
$importFile = 'files/import_city_country.csv';
$completeResult = readCSV($importFile);
$dataFile = $completeResult[0];
$maxLines = $completeResult[1];
for ($row = 1; $row < $maxLines; ++ $row) {
$countryData = array();
if(!is_null($dataFile[$row][0]))
{
// Define parameters for the queries
$params =array(
"nameCountry" => trim($dataFile[$row][0]),
"nameTown" => trim($dataFile[$row][1]),
"uuid" => uniqid(),
);
# Now check if we know that country already to avoid double entries
$queryString = '
MATCH (c:Country {name: {nameCountry}})
RETURN c
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
if(COUNT($result)==0) // Country doesnt exist!
{
$queryString = '
MERGE (c:Country {name: {nameCountry}} )
set
c.uuid = {uuid},
c.created = timestamp()
RETURN c
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
}
# Now check if we know that town already
$queryString = '
MATCH (t:Town {name: {nameTown}})
RETURN t
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
if(COUNT($result)==0) // Town doesnt exist!
{
$queryString = '
MERGE (t:Town {name: {nameTown}} )
set
t.created = timestamp()
RETURN t
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
// Relate town to country
$queryString = '
MATCH (c:Country {name: {nameCountry}}), (t:Town {name: {nameTown}})
MERGE (t)-[:BELONGS_TO]->(c);
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
}
} // Excel Last Line is not Null - go on
} // Next Row
?>
A typical CSV line looks like
Country City
Albania Tirana
This all works fine - but it takes more than 30 minutes on a pc to import 9.000 lines. I know the system needs to check each record if already existing and also do a relation between town and country but it seems quite long though for such an amount of CSV-lines.
Do you have maybe suggestions how to improve the import code?
Thanks,
Balael
BTW: Any chance to insert here code without editing every row and adding 4 spaces - kinda boring for longer code.....
Use LOAD CSV inside of the neo4j-shell if at all possible, and don't write your own code to process the CSV.
What this will do for you primarily is to allow you to batch many items into a single transaction USING PERIODIC COMMIT.
If you want to use the REST API remotely (as I assume you're doing here) then look into your language binding's support for batch operations. Your code as written is going to spend a lot of time going back and forth to the server, probably turning each line of the CSV into a request/response, which will be slow. Better to batch up many at a time and run them as one operation, which will help minimize how much protocol overhead you have.
I just had a framework for creating charts and this is how it works normally.
$p = new chartphp();
$p->data = array(array(
array("A",2),
array("B",3),
array("C",23),
array("D",10)
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
This way it works perfectly fine, now I need to get results from a sql query and fill the array.
$query ="SELECT t.date AS dates,COUNT(t.id) AS trans FROM Gab AS g, Transaction AS t WHERE t.date BETWEEN '2015-07-30' AND '201-07-10' AND g.TID = '1401009' ORDER BY DATES";
$ask = mysql_query($query) or die("Error");
//Now I try to load the results into the array to be integrated into the API.
$p = new chartphp();
$p->data = array(array(
while($recon = mysql_fetch_array($ask)
{
array($recon['dates'],recon['trans']),
}
));
$p->chart_type = "bar";
// Common Options
$p->xlabel = "My X Axis";
$p->ylabel = "My Y Axis";
$out = $p->render('c1');
I tried this but it does not work, the array dont seem to be loaded !
I'm actually not sure what nesting a while like you have would do and I'm unable to experiment at the moment, but something like this should get you in the right direction:
$p->data = array(array());
while($recon = mysql_fetch_array($ask))
{
$p->data[0][] = array($recon['dates'], $recon['trans']);
}
Initializing the array and then appending the elements in the loop.
im trying to pull out a menu in this json format :
check the output : http://www.alacarta.do/iphone/webservices/restaurants_menu2.php?r=415
The thing is that iterating of the Category plates, it duplicates the plates and then add the corresponding correct ones in each Category. all the time. check the output in the link. first category is TO SHARE. and the plates are ok, but the second category FRIES BAR, will throw again the plates from TO SHARE and then the correct plates in its category
<?
$where = empty($_GET['r'])? NULL : 'id = '. intval($_GET['r']);
$restaurant = $cmp->empresas($where,"nombre ASC")->fetch();
$json = array();
$arraynombre = array();
while($orden = $cmp->platos_tipos_orden("id_empresa = {$restaurant->id}","orden ASC")->foreachrow()):
$tipo = $cmp->platos_tipos("id = {$orden->id_tipo}")->fetch();
while($menu = $cmp->platos_menu("id_tipo = {$orden->id_tipo} AND id_empresa = {$orden->id_empresa}")->foreachrow()):
$p = $cmp->platos_lista("id = {$menu->id_plato}")->fetch();
$pnombre = $p->nombre;
$pid = $p->id;
$pprecio = $p->precio;
$arraynombre1 = array('plato_id'=>$pid,'plato_nombre'=>$pnombre,'precio'=>$pprecio);
if (in_array($arraynombre1['plato_id'], $arraynombre['plato_id'])) continue;
$arraynombre[] = $arraynombre1;
endwhile;
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
$json[] = $jsondata;
endwhile;
echo json_encode( array("menu"=>$json));
?>
Your issue is probably this line -
$arraynombre[] = $arraynombre1;
as you continually add to the array, not overwrite the previous loops values.
Try adding a key to it that is unique to each loop, ie. $orden->id_tipo -
$arraynombre[$orden->id_tipo][] = $arraynombre1;
Then you would also need to change
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre);
to
$jsondata = array('tipo'=> utf8_decode($tipo->nombre),'platos' => $arraynombre[$orden->id_tipo]);
note- it is hard to follow all your code logic, so [$orden->id_tipo] might need to be [$orden->id_empresa] or could be a similar counter var [$x] that you increase on each loop.
i am confused about how to extract values from a query, and place them into specific variable, when i don't know before hand what the name of the value will be.
it might be easier to show you what i mean.
the images below are the returned values, grouped by heading i.e Total_responded, Percent_responded etc.
so the first row will have under the column Responce the value Poached with a Percent_responded of 16.66667.
however the next row will have under column Responce $scrambled with a Percent_responded of 83.333333
i now want to place each of these values into individual variables like:
$poached , $poachedPercentage, $scrambled, $scrambledPercentage etc
i attempted to do it below, but produced the wrong figures. this is also not a cost effective way to do it. so, i would really appricaite some advice on how to extract the values
$getPollResult = results();
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce = safe_output(round($row['RESPONCE']));
$percentage = safe_output(round($row['Percent_responded']));
if($responce = 'Poached')
{
$percentageOne = $percentage;
$poached = $responce;
}
if ($responce = 'Scrambled')
{
$percentageTwo = $percentage;
$scrambled = $responce;
}
// echo " $percentagePoached $percentageScrambled ";die();
}
Use
$responce = trim($row['RESPONCE']);
Instead Of
$responce = safe_output(round($row['RESPONCE']));
Also, Change in if condition = to ==.
you can use "variable variables" (PHP Docs) to achieve that:
while ($row = mysqli_fetch_array ($getResult , MYSQLI_ASSOC))
{
$responce_name = trim($row['RESPONCE']);
$percentage_name = $responce_name . "Percentage";
$percentage = safe_output(round($row['Percent_responded'])); //don't know what safe_output() does
$$percentage_name = $percentage; //notice the double "$" here
}
your PHP variables will then look like this:
$PoachedPercentage = 17;
$ScrambledPercentage = 83;
// and so on....