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']. '
' .$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 Asst Manager');
where 003 is the $currempno 002 is the $currsupervisor Jane Doe Asst 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
Asst 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']. '
' .$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'].'
'.$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']. '
' .$row['Title'];
$orgArray[] = array($currempno, $currsupervisor, $currtitle);
}
var_dump($orgArray);