Archivi categoria: PHP

Calcolare la distanza euclidea tra due sequenze numeriche in php

In questo articolo calcoliamo la distanza euclidea di due serie numeriche molto semplici:

A (0,1,0)

B (0,5,10)

La distanza euclidea ci dice quanto le due serie sono simili tra di loro. Nel caso in cui il risultato è zero,le due serie sono uguali. Più la distanza euclidea è maggiore, più le due serie differiscono.

In php definiamo le serie come array:

$seqA=array(10,1,0);
$seqB=array(0,5,10);

Possiamo stampare uno qualsiasi dei valori degli array indicando il numero tra parentesi quadre accanto alla sequenza: Se per esempio vogliamo mostrare il primo valore della sequenza A, dobbiamo chiamare il valore 0 (cioè il primo valore) dell’array seqA.

echo $seqA[0] darà come risultato 10.

Ora stabiliamo delle coppie di array per ogni valore numerico (3) degli array di partenza:

$arraycoppia1= array($seqA[0],$seqB[0]);
$arraycoppia2= array($seqA[1],$seqB[1]);
$arraycoppia3= array($seqA[2],$seqB[2]);

Modifichiamo l’ordine dei valori degli array in base alla grandezza:

sort($arraycoppia1);
sort($arraycoppia2);
sort($arraycoppia3);

Ora calcoliamo le singoli distanze euclidee per ogni valore degli array coppia:

$de1=$arraycoppia1[1]-$arraycoppia1[0];
$de2=$arraycoppia2[1]-$arraycoppia2[0];
$de3=$arraycoppia3[1]-$arraycoppia3[0];

Per trovare la distanza euclidea tra i due array di partenza basta sommare le distanze euclidee singole:

$de= $de1+$de2+$de3;

Per trovare la distanza euclidea tra sequenze lunghe:

$seqA=array(0,1,0,5,4,…,n);
$seqB=array(0,5,10,4,5,..,n);

for($x = 0; $x <= 5; $x++) {

if(isset($de0)){

}else{ $de0 = 0;
}

$arraycoppia= array($seqA[$x],$seqB[$x]);
sort($arraycoppia);
$de= $arraycoppia[1]-$arraycoppia[0];
$de1=$de+$de0;
$de0=$de1;

}

echo $de1;

How to extract a single column values from CSV file in PHP

Importing data from a CSV file with PHP may mean you need to store or print just the results of a single and specific column of the table. To make an example, in the following case, I need to extract data from “color” column:

fruit, color, price
tomatoes, red, 0.08
oranges, orange, 0.12
bananas, yellow, 0.12

To extract the single color column from the table, fgetcsv PHP function can be used. This function returns each line values from a CSV table. In the loop, changing the value of $c variable, will output results of each line starting from $c variable value. Now remove $num variable and add  $c=0; $c < 1 (if just first column is wanted) [or $c=1; $c < 2 for second column or also $c=0; $c < 2 for first and second columns and so on] prevents to print all the following columns of the table, restricting results to a single column:

FGETCSV Basic Usage (Extracts all columns results line by line):

 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
 FGETCSV COLUMN “1” EXTRACTION (Extracts just first column results):
 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < 1; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
 FGETCSV COLUMN “2” EXTRACTION (Extracts just second column results):
 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=1; $c < 2; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
 FGETCSV COLUMN “3” EXTRACTION (Extracts just third column results):
 <?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=2; $c < 3; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

How to store WordPress Post Content in to a PHP variable

If you are developing something with WordPress you may need to create a variable in which to insert the content of a post. Something like:

$content = ..post content..

Classic the_content() function just prints the content of the article but does not allow to save it as a variable, unless you use content buffer. On the other hand  the content can be easily stored into a variable using get_the_content() function, even if if it does not return the content in the same way the_content() does it, since text is unformatted.

You can call get_the_content() function even outside the loop using the global variable $post:

global $post;
$content = $post->post_content;
In so doing post content will be saved within the $content variable and will then be available to you when you want to use it.

Str_replace that En Dash (or minus sign)! How to fix the problem when it’s not working

Building my first theme on WordPress I had been a very long time in to understand how to use str_replace function to change title of a page to remove all the words following another. This was approximately the string to change: i had name and surname of a specific person (John Doe) and what i wanted to do was to remove all the rest of the phrase.

Page Title:  John Doe Contact Page – Sitename

String i wanted to get as result after str_replace:  John Doe

So practically i had to get just “John Doe” from that page title. The easiest way i knew was to use str_replace function in PHP in the following way:

  • Getting the WordPress Title as a variable:

<?php

$string = get_the_title();
$replace = ” Contact Page – Sitename”;
$replacewith   = ” “;

?>

  • Then using str_replace to change the title and print the result:

<?php

$string = str_replace($replace, $replacewith, $string);

?>

Unfortunately first attempts didn’t working and the result i got was just the input string ($string) without any replacement. Then i just cruised on the internet and after failed attempts to understand why i didn’t get my hoped result I decided to try to remove just the last word of the input string to check str_replace function was actually working.

Input:  John Doe Contact Page – Sitename

String i wanted to get as result after str_replace:  John Doe Contact Page –

Well, it worked. So i realized that probably the issue was that dash in the middle of the title. To be honest I did not know it was called “dash”, I just used to call it “minus” and type it very simply using these keyword keys:

But, it was so. And i found there’s not just one dash but as many as 5 different types, two of which very very similar to each other. Wikipedia explain fairly clearly the difference between them.

So, you can figure out that figure dash and en dash are pretty similar each other, and they are also different from the minus sign (-) of the keyboard. Opening page source in the browser I got confirmation that in my case it was a endash, then sign was not show as itself but with HTML/XML numeric character reference &#8211; from which i could understand what it was.

At this point I repeated the str_replace on my string just not using the sign but the appropriate HTML/XML code (previously I was using “minus” sign).

This was the page title as well as it appeared on the browser:
John Doe Contact Page – Sitename

This was my wrong way to write it:
John Doe Contact Page – Sitename

The properly way to str_replace an endash sign:
John Doe Contact Page &#8211; Sitename