I'm trying to create a sort of multidimensional array which takes 2 values from a database and stores in into 1 index in the array
Example x[0] = Jille, 595
I'm doing this as such
while ($row = mysql_fetch_array($result2))
{
$opponents[] = $row['opponents'];
$fixId= array($row['fixture_id'] => $opponents) ; //Is this line correct??
}
Then later on in my code I want to use the $fixId array which should hold 2 values per index
I do this as such:
foreach($fixid as $id => $oppname){
echo "<option value=\"$oppname\" >".$oppname;"</option>";
}
However it is not working the values $id and $oppname does not have a value or take on some strange value.
What am I doing wrong?
You can do it like that :
while ($row = mysql_fetch_array($result2))
{
$opponents[] = array('oppname' => $row['opponents'], 'oppid' => $row['fixture_id']) ;
}
foreach ($opponents as $opp) {
echo '<option value="'.$opp['oppid'].'">'.$opp['oppname'].'</option>';
}
Try this:
$fixId = array();
while ($row = mysql_fetch_array($result2))
{
$opponents[] = $row['opponents'];
$fixId[] = array('fixture_id' => $opponents) ;
}
I made this test:
<?php
$fixId = array();
$opponents[] ="Jille, 595";
$fixId[] = array('fixture_id' => $opponents) ;
var_dump($fixId);
?>
Showing: array(1) { [0]=> array(1) { ["fixture_id"]=> array(1) { [0]=> string(10) "Jille, 595" } } }
Related
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 been trying to store the results of a MySQL query in a PHP array, however I have been struggling to access the values after they have been stored.
I used this to store the query:
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
Which when showing the array with var_dump gives an output similar to this, just with more values:
array(147) { [0]=> array(1) { ["TABLE_NAME"]=> string(8) "_3085515" } }
I want to be able to access the value with the _NUMBER, but I can't figure out how to do this?
1st : Declare the variable as a array
$array = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
2nd : Access the value like this
$array[0]['TABLE_NAME']
Do like that.
$array = [];
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
After 1st answer my output is one value missing my ratting lenght is According to Array2 not Array !,,,,,Input:
I want this output:
My output is getting 0,0,0,0
I want to compare two arrays with different length, if matches the add the value, if not then add "0" and skip after assign and go to first loop
My code:
for($i=0;$i<count($custt1);$i++){
for($j=0;$j<count($items);$j++){
if($items[$j]==$custt1[$i]){
$x[$j]=$rating[$j];
}
else{
$x[$j]=0;
}
}
for($j=0;$j<count($items1);$j++){
if($items1[$j]==$custt1[$i]){
$y[$j]=$rating1[$j];
}
else{
$y[$j]=0;
}
}
}
I want to save in x and y array if value present then add rating otherwise "0" and go to first loop but I am facing in index 0 if value not present add 0 and on 8 indexes. Hope you understand my explanation and please help me to solve this.
now my output is by applying 1st answer
<br />
<b>Notice</b>: Undefined offset: 5 in
<b>C:\xampp\htdocs\Rest\new2.php</b> on line
<b>79</b>
<br />
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 0
[4] => 5
[5] =>
[6] => 0
[7] => 0
[8] => 0
)
Because i am implementing recommendation system
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "hfc";
$array;
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($connection) {
$sql1="SELECT item_name
from feedback
GROUP BY item_name";
$sql="SELECT customer_email_address AS customeremail,
GROUP_CONCAT(
DISTINCT CONCAT(cook_email_address,'-',item_name,'-',rating)
) AS uniqueItem
FROM feedback
GROUP BY customer_email_address";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($result))
{
$customer_email[] = $row['customeremail'];
$cust1[]= $row['uniqueItem'].",";
}
$item[] = explode(",",$cust1[0]);
for($i=0;$i<count($item[0])-1;$i++){
$item_rating[] = explode("-",$item[0][$i]);
}
print_r ($item_rating);
for($i=0;$i<count($item_rating);$i++){
$items[]=$item_rating[$i][1];
$rating[]=$item_rating[$i][2];
}
$item1[] = explode(",",$cust1[1]);
for($i=0;$i<count($item1[0])-1;$i++){
$item_rating1[] = explode("-",$item1[0][$i]);
}
print_r ($item_rating1);
for($i=0;$i<count($item_rating1);$i++){
$items1[]=$item_rating1[$i][1];
$rating1[]=$item_rating1[$i][2];
}
$result1 = mysqli_query($connection, $sql1);
while ($row = mysqli_fetch_array($result1))
{
$custt1[]= $row['item_name'];
}
print_r ($custt1);
print_r ($items);
$output = array();
foreach ($custt1 as $i =>$item) {
if (in_array($item, $items)) {
$output[] = $rating[$i];
} else {
$output[] = 0;
}
}
print_r ($output);
for($i=0;$i<count($custt1);$i++){
for($j=0;$j<count($items);$j++){
if($items[$j]==$custt1[$i]){
$x[$i]=$rating[$j];
}
else{
$x[$i]=0;
}
}
for($j=0;$j<count($items1);$j++){
if($items1[$j]==$custt1[$i]){
$y[$j]=$rating1[$j];
}
else{
$y[$j]=0;
}
}
}
print_r ($x);
print_r ($y);
for($i1=0;$i1<count($custt1);$i1++)
{
$array[]=explode(",",$custt1[$i1]);
}
// echo count($array);
// print_r($custt1)."<br>";
/*for($i=0;$i<count($array);$i++)
{
for($y=1;$y<count($array);$y++)
{
$pearson=Corr($array[$i],$array[$y],$c=count($array));
}
}*/
$pearson=Corr($array);
echo $pearson;
}
function Corr(&$arr){
$x=$arr[0];
$y=$arr[1];
$length=count($x)-1;
$mean1=array_sum($x)/ $length;
$mean2=array_sum($y)/ $length;
echo $mean1."mean of x";
echo $mean2."mean of y";
echo "\n";
//echo $mean2;
$a=0;
$b=0;
$axb=0;
$a2=0;
$b2=0;
for($i=0;$i<$length;$i++)
{
$a=$x[$i]-$mean1;
$b=$y[$i]-$mean2;
$axb=$axb+($a*$b);
$a2=$a2+ pow($a,2);
$b2=$b2+ pow($b,2);
$corr= $axb / sqrt($a2*$b2);
}
return $corr;
}
?>
Use in_array() to tell if the element of array 1 is in array 2.
$output = array();
foreach ($array1 as $i => $item) {
if (in_array($item, $array2)) {
$output[] = $rating[$i];
} else {
$output[] = 0;
}
}
I am trying to retrieve records in MySQL DB.I want to retrieve all the records belong to the img_path column.from the following code I am getting results as an array.but iw ant them as separate variables.
My code
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = array(
'img_path' => $row['img_path'],
);
}
print_r($productitems);
Current Output
Array (
[0] => Array ( [img_path] => img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png )
[1] => Array ( [img_path] => img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg )
[2] => Array ( [img_path] => img ) )
expected output
$variable1 = img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png;
$variable2 = img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg;
You can use extract function like this:
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = $row['img_path'];
}
extract($productitems, EXTR_PREFIX_ALL, "variable");
echo $variable_0;
echo $variable_1;
echo $variable_2;
You can do that :
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $k => $row) {
$varName = 'var' . $k;
$$varName = array(
'img_path' => $row['img_path'],
);
}
And you will have access to $var0, $var1, and so forth.
You might use, extract() function. Docs here
The extract() function imports variables into the local symbol table
from an array.
This function uses array keys as variable names and values as variable
values. For each element it will create a variable in the current
symbol table.
This function returns the number of variables extracted on success.
Use list().
http://php.net/manual/en/function.list.php
From the manual:
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
You can also use the following code, where you do not need to use an additional function like list() or extract(). It is also a very minimalistic approach.
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $key => $row) {
${'img_path_'.$key} = $row['img_path'];
}
/*
Output:
["img_path_0"]=>
string(50) "img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png"
["img_path_1"]=>
string(50) "img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg"
["img_path_2"]=>
string(3) "img"
*/
So I have successfully wrote a script that will prepare and bind any parameters to a sql query but I am having trouble on the binding results part.
Here is my script:
public function query( $query_string, $params = null, $param_types = null) {
//prepare the statement
$stmt = $this->db->prepare($query_string);
//check if the sql query is wrong.
if($stmt === false) {
echo "Wrong SQL: " . $query_string . "<br />Error: " . $this->db->errno . " " . $this->db->error;
}
if($params != null && $param_types != null) {
//build the array that needs to pass the args to bind_param.
$a_params = array();
$a_params[] = &$param_types;
for($i=0; $i<count($params); $i++)
$a_params[] = &$params[$i];
// $stmt->bind_param('s', $param); equivalent
call_user_func_array(array($stmt, 'bind_param'), $a_params);
}
//run the query
$stmt->execute();
$data = $stmt->result_metadata();
$fields = array();
$out = array();
$count = 0;
while($field = $data->fetch_field()) {
$fields[$count++] = &$out[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $fields);
$results = array();
$k = 0;
// loop through all result rows
while ($stmt->fetch()) {
$results[$k++] = $out;
print_r($out);
echo "<br />";
}
$stmt->close();
return $results;
}
It seems to bind correctly when I output with print_r, but when I add to an array to return (for use in later script it has odd behavior).
Example call to the method:
$users = $TCS->query("SELECT name, age, id FROM test");
foreach($users as $user) {
echo $user['name'] . ': <br />';
echo ' age: ' . $user['age'] . '<br />';
echo ' id: ' . $user['id'] . '<br />';
}
But here is my output:
Array ( [name] => jake [age] => 18 [id] => 1 )
Array ( [name] => ryan [age] => 19 [id] => 2 )
Array ( [name] => stephen [age] => 16 [id] => 3 )
stephen:
age: 16
id: 3
stephen:
age: 16
id: 3
stephen:
age: 16
id: 3
TL;DR
Change $results[$k++] = $out; to $results[$k++] = array_flip(array_flip($out));
Here is an explanation of what is happening.
var_dump($out);
// first iteration
array(2) {
["name"]=>
&string(4) "mike"
["id"]=>
&int(1)
}
// second interation
array(2) {
["name"]=>
&string(6) "amanda"
["id"]=>
&int(2)
}
The important point to notice here are the ampersands, they mean that the values of id and name are references. What those references are pointing to will be changed when $out['id'] and $out['name'] are. Thus the statement $results[$k++] = $out; means copy $out and assign it to $results[$k], this includes copying the references. In the next iteration what is being referenced in $results[$k-1] is changed to the new values behind your back.
Here is a simple example;
$i = 1;
$a = array('id' => &$i);
$b = $a;
$i = 2;
var_dump($a,$b);
// output
array(1) {
["id"]=>
&int(2)
}
array(1) {
["id"]=>
&int(2)
}
You can fix this by modifying the line:
$results[$k++] = $out; to $results[$k++] = array_flip(array_flip($out));
The inner array_flip will dereference the values and make them keys, the outer flip reverse the process.
But I would suggest rewriting everything below $stmt->execute() as follows.
//run the query
$stmt->execute();
$result = $stmt->get_result();
if (!$result) { return array(); }
$ret = array();
while ($row = $result->fetch_assoc()) {
array_push($ret, $row);
}
return $ret;