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;
}
}
Related
I have an array in PHP which is established from my database, which will be formatted as such:
[ "Folder1",
["Content1", "Content2", "Content3"],
"Folder2",
["Content1", "Content2", "Content3"]
]
I have the current code for this process
<?php
$sql = ("SELECT FlashCardFolderName, FlashCardSetName FROM FlashCardFolders, FlashCardSets WHERE FlashCardFolderUserID = " . $_SESSION["id"] . " AND FlashCardSetFlashCardFolderID = FlashCardFolderID ORDER BY FlashCardFolderName");
$result = $db->get_con()->query($sql);
if($result->num_rows > 0){
$temp = "";
$foldersAndSets = array();
$tempSet = array();
while ($row = $result->fetch_assoc()){
if($temp===$row["FlashCardFolderName"]){
array_push($tempSet, $row["FlashCardSetName"]);
} else{
array_push($foldersAndSets, $tempSet);
$tempSet = array();
array_push($foldersAndSets, $row["FlashCardFolderName"]);
array_push($tempSet, $row["FlashCardSetName"]);;
$temp = $row["FlashCardFolderName"];
}
}
array_push($foldersAndSets, $tempSet);
array_shift($foldersAndSets);
echo json_encode($foldersAndSets);
} else{
echo "<h6>Looks like there's nothing here...</h6>";
}
$length = sizeof($foldersAndSets);
for ($i = 0; $i < $length; $i++){
$secondDimension = sizeof($foldersAndSets[$i+1]);
for($j = 0; $j < $foldersAndSets; $j++) {
echo "$foldersAndSets[$i][$j+1]";
}
}
?>
But it seems it's not working the way I want it to. Any ideas as to what I could be doing wrong?
First of all I'm suggestion to you to make a useful format of your input data, I mean it would be better to reformat your input array. For example, with structure like Folder -> array of Contents:
$reformatted = [];
$tmp = '';
foreach($foldersAndSets as $ind=>$txt){
if ($ind % 2 == 0){ // if this is a 1-st, 3-rd, 5-th etc value -> Folders
$reformatted[$txt] = [];
$tmp = $txt;
} else { // if this is a 2-nd, 4-th etc value -> Content
$reformatted[$tmp] = $txt;
}
}
This will create an array like:
Array
(
[Folder1] => Array
(
[0] => Content1
[1] => Content2
[2] => Content3
)
[Folder2] => Array
(
[0] => Content1
[1] => Content2
[2] => Content3
)
)
With this array you can work in further. Now you can get any value you need with help of a simple foreach loop:
foreach($reformatted as $fold=>$cont){
echo $fold.PHP_EOL.PHP_EOL;
foreach($cont as $item){
echo $item.PHP_EOL;
}
echo PHP_EOL;
}
Output:
Folder1
Content1
Content2
Content3
Folder2
Content1
Content2
Content3
Demo
Note: you can replace your second part(from $length = sizeof($foldersAndSets); and below) of code with this.
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" } } }
I have an array which comes from a report.
This report has info similar to:
157479877294,OBSOLETE_ORDER,obelisk,19/01/2013 01:42pm
191532426695,WRONG_PERFORMANCE,g3t1,19/01/2013 01:56pm
159523681637,WRONG_PERFORMANCE,g3t1,19/01/2013 01:57pm
176481653889,WRONG_PERFORMANCE,g4t1,19/01/2013 01:57pm
167479810401,WRONG_PERFORMANCE,g4t1,19/01/2013 02:00pm
172485359309,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
125485358802,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
172485359309,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
125485358802,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
What I need to do is get the total of each type of error and the location so for the first would be error: 'OBSOLETE_ORDER' and location: 'obelisk'. I have tried to do this a number of ways but the best I can come up with is a multi dimensional array:
$error_handle = fopen("$reportUrl", "r");
while (!feof($error_handle) )
{
$line_of_text = fgetcsv($error_handle, 1024);
$errorName = $line_of_text[1];
$scannerName = $line_of_text[2];
if($errorName != "SCAN_RESULT" && $errorName != "" && $scannerName != "SCAN_LOGIN" && $scannerName != "")
{
$errorsArray["$errorName"]["$scannerName"]++;
}
}
fclose($error_handle);
print_r($errorsArray);
gives me the following:
Array ( [OBSOLETE_ORDER] => Array ( [obelisk] => 1 ) [WRONG_PERFORMANCE] => Array ( [g3t1] => 2 [g4t1] => 2 [g4t2] => 2 ) [DAY_LIMIT_EXCEEDED] => Array ( [obelisk] => 2 ) )
which is great...except how do I then take that apart to add to my sql database?! (I am interested in getting the key and total of that key under the key the array is under)
and then add it to the tables
-errors-
(index)id_errors
id_event
id_access_scanner
id_errors_type
total_errors
-errors_type-
(index)id_errors_type
name_errors_type
-access_scanner-
(index)id_access_scanner
id_portal
name_access_scanner
PLEASE HELP!
Thanks!
A multidimensional array is more than you need. The approach to take is to create your own string ($arrayKey in my example) to use as an array key that combines the scanner name and the error so that you can get a count.
//this is the array containing all the report lines, each as an array
$lines_of_text;
//this is going to be our output array
$errorScannerArray = array();
//this variable holds the array key that we're going to generate from each line
$arrayKey = null;
foreach($lines_of_text as $line_of_text)
{
//the array key is a combination of the scanner name and the error name
//the tilde is included to attempt to prevent possible (rare) collisions
$arrayKey = trim($line_of_text[1]).'~'.trim($line_of_text[2]);
//if the array key exists, increase the count by 1
//if it doesn't exist, set the count to 1
if(array_key_exists($arrayKey, $errorScannerArray))
{
$errorScannerArray[$arrayKey]++;
}
else
{
$errorScannerArray[$arrayKey] = 1;
}
}
//clean up
unset($line_of_text);
unset($arrayKey);
unset($lines_of_text);
//displaying the result
foreach($errorScannerArray as $errorScanner => $count)
{
//we can explode the string hash to get the separate error and scanner names
$names = explode('~', $errorScanner);
$errorName = $names[0];
$scannerName = $names[1];
echo 'Scanner '.$scannerName.' experienced error '.$errorName.' '.$count.' times'."\n";
}
$list = array();
foreach ($lines as $line) {
$values = explode(',' $line);
$error = $values[1];
$scanner = $values[2];
if (!isset($list[$error])) {
$list[$error] = array();
}
if (!isset($list[$error][$scanner])) {
$list[$error][$scanner] = 1;
} else {
$list[$error][$scanner]++;
}
}
To go through each result I just did the following:
foreach ($errorsArray as $errorName=>$info)
{
foreach ($info as $scannerName=>$total)
{
print "$errorName -> $scannerName = $total </br>";
}
}
and now will just connect it to the sql
With your edited question, this much simpler loop will work for you, you just need to then insert the data into your database inside the loop, instead of echoing it out:
$errorsArray = Array (
[OBSOLETE_ORDER] => Array (
[obelisk] => 1
)
[WRONG_PERFORMANCE] => Array (
[g3t1] => 2
[g4t1] => 2
[g4t2] => 2
)
[DAY_LIMIT_EXCEEDED] => Array (
[obelisk] => 2
)
)
foreach($errorsArray as $row => $errors) {
foreach($errors as $error => $count) {
echo $row; // 'OBSOLETE_ORDER'
echo $error; // 'obelisk'
echo $count; // 1
// insert into database here
}
}
OLD ANSWER
You just need a new array to hold the information you need, ideally a count.
Im assuming that the correct data format is:
$report = [
['157479877294','OBSOLETE_ORDER','obelisk','19/01/2013 01:42pm'],
['191532426695','WRONG_PERFORMANCE','g3t1','19/01/2013 01:56pm'],
['159523681637','WRONG_PERFORMANCE','g3t1','19/01/2013 01:57pm'],
['176481653889','WRONG_PERFORMANCE','g4t1','19/01/2013 01:57pm'],
.....
];
foreach($report as $array) {
$errorName = $array[1];
$scannerName = $array[2];
if(exists($errorsArray[$errorName][$scannerName])) {
$errorsArray[$errorName][$scannerName] = $errorsArray[$errorName][$scannerName] + 1;
}
else {
$errorsArray[$errorName][$scannerName] = 1;
}
}
Here is example which I have try
<?php
include 'spider/classes/simple_html_dom.php';
$html = new simple_html_dom();
$html->load("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");
$e = $html->find("h2", 0);
$key = array();
if($e->plaintext != ""){
foreach($html->find("h2", 0) as $e){
//echo $e->plaintext;
array_push($key, $e->plaintext);
}
} else {
echo "error";
}
print_r($key);
?>
Result:
Array ( [0] => [1] => [2] => [3] => [4] => [5] => Heading 1This heading 2
[6] => [7] => )
How Do i use array_push to create an array?
What happens, when you try this code?
I removed the first "find" and i also found an example on the internet, where the second param of "find" was not set.
<?php
include 'spider/classes/simple_html_dom.php';
$html = new simple_html_dom();
$html->load("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");
$key = array();
if(isset($html)){
foreach($html->find("h2") as $e){
//echo $e->plaintext;
array_push($key, $e->plaintext);
}
} else {
echo "error";
}
print_r($key);
?>
Explanation:
// Find all anchors, returns a array of element objects
$ret = $html->find('a');
// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);
Here's an alternative with the default DOMDocument class.
$html = new DOMDocument('1.0','utf-8');
$html->loadHTML("<html><body><h2>Heading 1</h2><h2>This heading 2</h2></p></p></body></html>");
$key = array();
$h2 = $html->getElementsByTagName('h2');
for ($i = 0; $i < $h2->length; $i++) {
array_push($key, $h2->item($i)->nodeValue);
}
print_r($key);
How can I assign query result into array elements?
This is my code:
include('db.php');
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Database connection error");
mysql_select_db($dbname);
$query = "select * from test where value=20";
$result = mysql_query($query);
$vegetable_list = array('$rice', '$wheat', '$potato', '$pulses');
$i = 1;
while($row_result = mysql_fetch_row($result))
{
??????? = $row_result[$i];
$i++;
}
How can I assign the query result into the array? Let's say:
$rice = $row_result[1];
$wheat = $row_result[2];
$potato = $row_result[3];
How I can assign the values automatically?
Let try:
$vegetable_list= array('rice','wheat','potato','pulses'); //no $ symbol
while($row_result=mysql_fetch_row($result))
{
foreach($vegetable_list as $k => $v)
${$v} = $row_result[$k + 1]; //I think mysql_fetch_row should indexing from 0 -> n (not from 1)
}
Ok not sure but seems like you have a 150column x 20rows table that you want to convert into a two dimensional array. It is as simple as this:
$data = array( );
while( $row = mysql_fetch_assoc( $result ) )
{
// at this point, $row contains a single row as an associative array
// keys of this array consist of column names
// all you need to do is append $row to $data
$data[ ] = $row;
}
// $data is a two dimensional array
// $data[ 0 ] contains 1st row
// $data[ 1 ] contains 2nd row
// ...
// $data[ 0 ][ 'rice' ] contains rice column value for 1st row
// $data[ 0 ][ 'wheat' ] contains wheat column value for 1st row
// ...
// $data[ 1 ][ 'rice' ] contains rice column value for 2nd row
// $data[ 1 ][ 'wheat' ] contains wheat column value for 2nd row
// ...
// and so on
var_dump( $data );
Edited the code.
Here:
include('db.php');
$conn=mysql_connect($dbhost,$dbuser,$dbpass) or die("Database connection error");
mysql_select_db($dbname);
$query="select * from test where value=20";
$result=mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$vegetable_list= array( array () );
$rcols = mysql_query("SHOW COLUMNS FROM test");
if (!$rcols) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
$i = 0;
$j = 0;
if (mysql_num_rows($result) == 0) {
echo "No rows found.";
} else {
while ($row = mysql_fetch_assoc($result)) {
while ($cols = mysql_fetch_assoc($rcols);) {
$vegetable_list[$i][$j] = $row[$cols['Field']];
$i++;
}
$j++;
}
}
} else {
//some error message
}
use switch case :
$i=1;
while($row_result=mysql_fetch_assoc($result))
{
switch($i) {
case 1 : $rice = $row_result[$i]; break;
case 2 : $wheat = $row_result[$i]; break;
}
$i++;
}
or you can do this :
$i=0;
$vegetable = array("rice", "wheat", "potato");
while($row_result=mysql_fetch_assoc($result))
{
$idx = 0;
foreach($row_result as $result){
${$vegetable[$i]}[$idx] = $result;
$idx++;
}
$i++;
}
then try to
var_dump($rice);
you should get array of your specific column.
The first thing is that, you dont need to make array element as variable.
You can simply write without dollar sign like : $rice as rice and so on.
$vegetable_list= array('rice', 'wheat', 'potato', 'pulses');
Now execute Select query to get the data from database
$query = "select * from test where value=20";
$result = mysql_query($query);
make while loop
while($row_result=mysql_fetch_row($result))
{
foreach($vegetable_list as $k => $v)
${$v} = $row_result[$k + 1];
from 0 -> n (not from 1)
}