Jonaii Jonaii - 4 months ago 16
PHP Question

How do I put a specific string from an array that came from a file in PHP?

Hi I have been doing this project for almost a month now. Is there's anyway I can store the value of the next string after the searched string in the list of array?

For example:

Deviceid.txt content is:

Created:21/07/2016 1:50:53; Lat:30.037853; Lng:31.113798; Altitude:79; Speed:0; Course:338; Type:Gps;
Created:21/07/2016 1:49:53; Lat:30.037863; Lng:31.113733; Altitude:60; Speed:0; Course:338; Type:Gps;


Here is my sample php coding

$file_handle = fopen("data/deviceid.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
array_push($a,$line);
}

$searchword = 'Lat';
$matches = array_filter($a, function($var) use ($searchword) {
return preg_match("/\b$searchword\b/i", $var);
});
print_r($matches);
fclose($file_handle);


Matches Data:
[0] = 30.037853
[1] = 30.037863

Answer

After parsing the file with the code below, you can use array_column (php v5.5.0+) to get all values from a specific key, like so:

array_column($parsed, 'Lat');

Output:

Array
(
    [0] => 30.037853
    [1] => 30.037863
)

See it in action here.


And here is the code to parse the content of the file:

// $a = each line of the file, just like you're doing

$a = array_filter($a); // remove empty lines

$parsed = array();

foreach($a as $v1){
    $a1 = explode(';', $v1);
    $tmp = array();
    foreach($a1 as $v2){
        $t2 = explode(':', $v2);
        if(count($t2) > 1){
            $tmp[trim(array_shift($t2))] = trim(  implode(':', $t2)  );
        }
    }
    $parsed[] = $tmp;
}

This is the structure of $parsed:

Array
(
    [0] => Array
        (
            [Created] => 21/07/2016 1:50:53
            [Lat] => 30.037853
            [Lng] => 31.113798
            [Altitude] => 79
            [Speed] => 0
            [Course] => 338
            [Type] => Gps
        )

    [1] => Array
        (
            [Created] => 21/07/2016 1:49:53
            [Lat] => 30.037863
            [Lng] => 31.113733
            [Altitude] => 60
            [Speed] => 0
            [Course] => 338
            [Type] => Gps
        )

)

See the code in action here.

Comments