I have 2 results set
$result_a = #pg_query($rquery_a);
$result_b = #pg_query($rquery_b);
I have 2 arrays to host and display the data on an html page:
$datas_a = array();
$datas_b = array();
$datas_a gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_occu' => $row['duree_resa']);
$i++;
}
and $datas_b gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
From these 2 existing arrays with same number of rows and same keys, I would like 3 columns, 1 column is the same for both arrays ($datas_a and $datas_b), the second column is from $datas_a and the third column is from $datas_b
It currently looks like this for $datas_a
$datas_a
It currently looks like this for $datas_b
$datas_b
It should look like this
merging columns
Now, I have used
$dataComb = array_merge($datas_a, $datas_b);
but it puts one array on top of the other while I would like to just add a column
try
$i=0;
foreach ($datas_a as $data) {
$dataComb[$i]["s1"] = $data["s1"];
$dataComb[$i]["duree_resa"] = $data["duree_resa"];
$i++;
}
$i=0;
foreach ($datas_b as $data) {
$dataComb[$i]["duree_cours"] = $data["duree_cours"];
$i++;
}
Edit - 2021-08-20
Or for something more robust given it's a basic way I only know to do this
$datas_a = array(); // associative array
$datas_b = array();
$dataComb = []; // indexed array
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_resa' => $row['duree_resa']);
$i++;
}
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
$i=0;
if($a>=$b){
foreach($datas_a as $dataa) {
$dataTmp[$i][0] = $dataa["s1"];
$dataTmp[$i][1] = $dataa["duree_resa"];
foreach($datas_b as $datab) {
if($dataa["s1"] == $datab["s1"] ){
$dataTmp[$i][2] = $datab["duree_cours"];
}
}
$i++;
}
}
elseif($a<$b){
foreach($datas_b as $datab) {
$dataTmp[$i][0] = $datab["s1"];
$dataTmp[$i][1] = $datab["duree_resa"];
foreach($datas_a as $dataa) {
if($datab["s1"] == $dataa["s1"] ){
$dataTmp[$i][2] = $dataa["duree_cours"];
}
}
$i++;
}
}
$nb_lig = $a>=$b ? $a : $b;
for ($row=0; $row<=$nb_lig; $row++) {
$dataComb[$row]["s1"] = $dataTmp[$row][0];
$dataComb[$row]["duree_resa"] = $dataTmp[$row][1];
$dataComb[$row]["duree_cours"] = $dataTmp[$row][2];
}
And there is $dataComb as an associative array that combines the data from previous arrays with matching records
foreach ($dataComb as $data){
echo '<tr>';
echo '<td>'.$data["s1"].'</td>';
echo '<td>'.$data["duree_resa"].'</td>';
echo '<td>'.$data["duree_cours"].'</td>';
echo '</tr>';
}
I have this code but when I run it it give me error ( Notice: Undefined offset: 1 in C:\wamp\www\test3.php on line $str[$row['term_no']] += ",".$row['code']; )
How can I solve this problem?
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, "uoh");
$q = " SELECT * FROM `degree_plan` LEFT JOIN courses ON
degree_plan.course_number=courses.course_number
where major='COE'";
$result = mysqli_query($con, $q);
if ($result) {
$str = [];
while ($row = mysqli_fetch_array($result)) {
{
$str[$row['term_no']] += "," . $row['code'];
}
foreach ($str as $key => $value) {
echo $value;
echo $key;
}
}
}
?>
In your code, you are puting all codes in one element which is never defined.
change this:
$str[$row['term_no']] += ",".$row['code'];
to this:
$str[$row['term_no']] = $row['code'];
The error happens because the array element doesn't exist, so, first check the element : if it exist, add, if it doesn't, create:
while($row = mysqli_fetch_array($result))
{
if ( isset( $str[$row['term_no']] ) ) // IF ELEMENT EXISTS...
$str[$row['term_no']] .= ",".$row['code']; // ADD TO ELEMENT.
else $str[$row['term_no']] = $row['code']; // CREATE ELEMENT.
}
Now I'm tryin' to sort MySQL result to multi-dimensional array by type line in SQL
so, that's my code:
function getTableValues($table_name)
{
// $link = connect_db();
$front_end_query = "SELECT * FROM `".$table_name."` WHERE `type` = 'front_end'";
$front_end_query_result = mysql_query($front_end_query);
$cur_row = 0;
/*while ($line = mysql_fetch_assoc($queryresult))
{
$values = $line;
$cur_row++;
}*/
$front_end = mysql_fetch_assoc($front_end_query_result);
$i=0;
while ($line = mysql_fetch_assoc($front_end_query_result)){
#if ($line['type'] === 'front_end'){
# $line[$line['type']][$line['name']] = $line['value'];
# $line[$line['type']][$line['name']]['desc'] = $line['description'];
# $line[$line['type']][$line['name']]['visible_name'] = $line['visible_name'];
# $line[$line['type']][$line['name']]['write_roles'] = $line['write_roles'];
# $line[$line['type']][$line['name']]['read_roles'] = $line['read_roles'];
#}
$values['front_end'][$line['name']] = $line;
$i++;
}
return $values;
}
And my MySQL table:
id type write_roles read_roles name value description visible_name
1 front_end 0 any title sometitle exampletitle Title
2 front_end 0 any description somedesc example Description
And that's what I want to get:
$config[(someType)][(SomeName)] = (value of line)
$config[(someType)][(SomeName)][(SomeOption)] = (value of option)
E.g.: $config['front_end']['title']['description'] that returns exampletitle
How I can do that?
UPD0: so I tried to echo my array with foreach, and it's returned just one row from my DB.
What I doing wrong?
$values = array(); //base array
while ($line = mysql_fetch_assoc($front_end_query_result)){ //fetch the rows
//in the base array create a new array under 'name'
$values[$line['name']] = array();
//for each item in the result set, add it to the new array
foreach ($line as $key => $value) {
$values[$line['name']][$key] = $value;
}
}
To give some context, a little while ago with the help from VolkerK on this very site I created a function that queries an Oracle database and places the content into a neatly formatted PHP array, depending on the index. Here's the original question.
The problem is, in some cases I just want to return a single value from a quick query, and when I do I get the the following error: Notice: Undefined index:
Here's the code I'm using:
function oracleGetData($query, $id = null) {
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
// remove one layer if there's only one record
if(count($results) == 1 and is_null($id)) {
$results = array_pop($results);
}
return $results;
}
I have tried changing the line that populates the array like so:
if(is_null($id)) {
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row ] = $row;
}
} else {
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
}
Basically if the $id variable is null, remove all references to it, but then I get a 'Warning: Illegal offset type' error.
Any help would be much appreciated, I've tried passing in the single field I require into the function but get the same error.
Thank you
Perhaps if $id is NULL you could just use sequential numbers for the indexes, as in:
function oracleGetData($query, $id = null)
{
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
if(is_null($id)) {
$idx = 1;
while (false!==($row=oci_fetch_assoc($sql))) {
$results[ $idx ] = $row;
$idx = $idx + 1;
}
} else {
while ( false!==($row=oci_fetch_assoc($sql))) {
$results[ $row[$id] ] = $row;
}
}
// remove one layer if there's only one record
if(count($results) == 1 and is_null($id)) {
$results = array_pop($results);
}
return $results;
}
Share and enjoy.
I am reading a 'kind' of csv file and exploding it and storing it in array.
The file I am reading has this structure
Id,Log,Res,File
mydb('Test1','log1','Pass','lo1.txt').
mydb('Test2','log2','Pass','lo2.txt').
mydb('Test3','log3','Pass','lo3.txt').
Now what I am trying to do is :
reading the last record in my database, get the Name, lets say in this case 'Test1' and then I am searching through my file and where I can find the position of 'Test1' and get the next lines in the file, extract the ID,s and add it to database.
I am getting the position of desired string in the file, but I am not sure how to get the next lines too.
Here's my code so far.
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("testing") or die(mysql_error());
$result = mysql_query("select ID from table_1 order by S_no DESC limit 1") or die(mysql_error());
$row = mysql_fetch_array( $result );
$a = $row['ID'];
echo 'Present Top Row is '.$a.'<br>';
$addresses = explode("\n", file_get_contents('\\\\fil1\\logs\\tes.pl'));
foreach($addresses as $val)
{
$pos = strstr($val, $a);
if ($pos === false) {
} else {
echo "The string <br> '$a' <br>was found in the string <br>'$val' <br>";
echo " and exists at position <br>$pos<br>";
}
}
Hope I understand you correctly. If so you could just set a flag once the item is found and then explode each line then on a ' character. The second value in the resultant array should then contain the id as per your example.
$addresses = explode("\n", file_get_contents('\\\\fil1\\logs\\tes.pl'));
$bFound = false;
foreach($addresses as $val)
{
if (!$bFound) {
$pos = strstr($val, $a);
if ($pos === false) {
} else {
echo "The string <br> '$a' <br>was found in the string <br>'$val' <br>";
echo " and exists at position <br>$pos<br>";
$bFound = true;
}
}
else {
$aCols = explode("'", $val);
$sId = $aCols[1];
// Now add Id as stored in $sId to DB here
}
}
If id is supposed to be unique, the traffic between the php process and the MySQL server is not the limiting factor and you have to parse each line anyway, you could create a unique index and let MySQL decide whether it accepts the record or not.
Simple example:
$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$pdo->exec('CREATE TEMPORARY TABLE foo (Id varchar(16),Log varchar(16),Res varchar(16),File varchar(16), unique key(Id))');
$stmt = $pdo->prepare('INSERT IGNORE INTO foo (Id,Log,Res,File) VALUES(?,?,?,?)');
$pattern = '/(?<=^mydb\().+(?=\)\.$)/';
$fp = 'dummy';
while ( false!==($row=dummy_fgets($fp)) ) {
if ( preg_match($pattern, $row, $m) ) {
$row = str_getcsv($m[0], ',', "'");
$stmt->execute($row);
echo $row[0], ' -> ', $stmt->rowCount(), "\n";
}
}
function dummy_fgets($dummy) {
static $data = array(
"mydb('Test1','log1','Pass','lo1.txt').\n",
"mydb('Test2','log2','Pass','lo2.txt').\n",
"mydb('Test3','log3','Pass','lo3.txt').\n",
// start again ...like you process the same file again + 1 new record
"mydb('Test1','log1','Pass','lo1.txt').\n",
"mydb('Test2','log2','Pass','lo2.txt').\n",
"mydb('Test3','log3','Pass','lo3.txt').\n",
"mydb('Test4','log3','Pass','lo3.txt').\n"
);
$rv = current($data);
next($data);
return $rv;
}
prints
Test1 -> 1
Test2 -> 1
Test3 -> 1
Test1 -> 0
Test2 -> 0
Test3 -> 0
Test4 -> 1