Remove Array junk from result - PHP - php

Looking on how to remove useless junk from result like:
] => Array ( [] =>
My PHP code:
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
print_r($result);
?>
Sample output:
Array ( [] => Array ( [] => slant distance ) [Atlantic Southeast Airlines flight 5520] => Array ( [] => 23 miles SW ) [Volaris flight 940] => Array ( [] => 30 miles NNW ) [American Airlines flight 386] => Array ( [] => 14 miles NW ) [American Airlines flight 296] => Array ( [] => 27 miles W ) [Central Air Southwest flight 7] => Array ( [] => 6.5 miles WSW ) )
At each break, there's a <hr> tag, not very important though.

Try this:
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value)
{
echo $key;
foreach($value as $value1){
echo $value1;
echo " ";
}
}

Related

how to Display values from nested array

Please help me to extract and display the values from this array..
This is the output when I do a print_r($array); :
Array
(
[0] => SPD Object
(
[DRIVERNAME] => SPD Barry
[STARTTIME] => 07:44
[FINISHTIME] => 18:12
[STOP] =>
[SEQUENCENO] => 37
[PLACENAME] => AMSTERDAM ZUIDOOST
[ARRIVALTIME] => 17:32
)
[1] => SPD Object
(
[DRIVERNAME] => SPD Brady
[STARTTIME] => 07:36
[FINISHTIME] => 15:53
[STOP] =>
[SEQUENCENO] => 32
[PLACENAME] => NIEUWEGEIN
[ARRIVALTIME] => 15:30
)
[2] => SPD Object
(
[DRIVERNAME] => SPD Bram
[STARTTIME] => 08:11
[FINISHTIME] => 18:32
[STOP] =>
[SEQUENCENO] => 32
[PLACENAME] => LAGE ZWALUWE
[ARRIVALTIME] => 17:28
)
)
What I want to do is, get this Driver Name and Sequence Number and echo them.
UPDATE :
My full code can be found below.
I get a xml file which contain this kind of stuff :
<TRIP>
<DRIVERNAME>SPD Barry</DRIVERNAME>
<STARTTIME>07:44</STARTTIME>
<FINISHTIME>18:12</FINISHTIME>
<STOP>
<SEQUENCENO>1</SEQUENCENO>
<PLACENAME>ROTTERDAM</PLACENAME>
<ARRIVALTIME>08:30</ARRIVALTIME>
</STOP>
</TRIP>
Here is my PHP file to collect data into an array.
<?php
class SPD {
function SPD ($aa) {
foreach ($aa as $k=>$v)
$this->$k = $aa[$k];
}
}
function readDatabase($filename) {
// read the XML database of aminoacids
$data = implode("", file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);
// loop through the structures
foreach ($tags as $key=>$val) {
if ($key == "TRIP") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i=0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}
function parseMol($mvalues) {
for ($i=0; $i < count($mvalues); $i++) {
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}
return new SPD($mol);
}
$db = readDatabase("test.xml");
if(is_array($db)){
foreach($db as $item) {
echo $item->DRIVERNAME;
echo $item->SEQUENCENO;
}
}
?>
What I want to do is, echo Driver name and Sequence Number :)
This should do it :
<?php
class SPD {
function SPD($aa) {
foreach ($aa as $k => $v)
$this->$k = $aa[$k];
}
}
function readDatabase($filename) {
// read the XML database of aminoacids
$data = implode("", file($filename));
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, $data, $values, $tags);
xml_parser_free($parser);
// loop through the structures
foreach ($tags as $key => $val) {
if ($key == "TRIP") {
$molranges = $val;
// each contiguous pair of array entries are the
// lower and upper range for each molecule definition
for ($i = 0; $i < count($molranges); $i+=2) {
$offset = $molranges[$i] + 1;
$len = $molranges[$i + 1] - $offset;
$tdb[] = parseMol(array_slice($values, $offset, $len));
}
} else {
continue;
}
}
return $tdb;
}
function parseMol($mvalues) {
for ($i = 0; $i < count($mvalues); $i++) {
if(isset($mvalues[$i]["value"])) {
$mol[$mvalues[$i]["tag"]] = $mvalues[$i]["value"];
}
}
return new SPD($mol);
}
$db = readDatabase("test.xml");
if (is_array($db)) {
foreach ($db as $item) {
echo 'ITEM 1 : ' . "\n<br/>";
echo '---------------' . "\n<br/>";
echo 'DRIVERNAME : ' . $item->DRIVERNAME . "\n<br/>";
echo 'SEQUENCENO : ' . $item->SEQUENCENO . "\n\n<br/><br/>";
}
}
?>

Count occurrence of words and only 1 in the same phrases

I have a problem where I need to count the number of times a word occurs in a given array.
I want the code to increase the count of a word ('instagrammm') by 1 if the word is in the same phrases.
Here is my code:
$output = array();
$buzzes = ['instagramm some text instagramm', 'instagramm some text' , 'instagramm some text' , 'instagramm some text'];
foreach ($buzzes as $buzz) {
$flag = 0;
$words = explode(" ",$buzz);
foreach ($words as $word)
{
$word = mb_convert_case($word, MB_CASE_LOWER, "UTF-8");
$word = preg_replace('/^[^A-Za-z0-9\-]|[^A-Za-z0-9\-]$/', '', $word);
if(strlen($word) > 2){
if (array_key_exists($word, $output)){
$output[$word]++;
}else{
$output[$word] = 1;
}
}
}
}
Here is the expected result:
Array
(
[instagramm] => 4
[some] => 4
[text] => 4
)
Try this one. It will be faster with fewer comparisons and allocations:
foreach ($buzzes as $buzz) {
$words = array_unique(explode(' ',$buzz));
foreach ($words as $word) {
$word = mb_convert_case($word, MB_CASE_LOWER, "UTF-8");
$word = preg_replace('/^[^A-Za-z0-9\-]|[^A-Za-z0-9\-]$/', '', $word);
if(strlen($word) > 2){
if (array_key_exists($word, $output)){
$output[$word]++;
}else{
$output[$word] = 1;
}
}
}
}
take a look:
// My version
Took: 0.178099
Array
(
[instagramm] => 4
[some] => 4
[text] => 4
)
// accepted version
Took: 25.308847
Array
(
[instagramm] => 4
[some] => 4
[text] => 4
)
seems you are suppose to have another condition in your piece of code.
just modified your code with a condition.
$output = array();
$buzzes = array('instagramm some text instagramm', 'instagramm some text' , 'instagramm some text' , 'instagramm some text');
foreach ($buzzes as $buzz) {
$flag = 0;
$words = explode(" ",$buzz);
$wordArr = array();
foreach ($words as $word)
{
$word = mb_convert_case($word, MB_CASE_LOWER, "UTF-8");
$word = preg_replace('/^[^A-Za-z0-9\-]|[^A-Za-z0-9\-]$/', '', $word);
if(!in_array(strtolower($word),$wordArr)) {
if(strlen($word) > 2){
if (array_key_exists($word, $output)){
$output[$word]++;
}else{
$output[$word] = 1;
}
}
$wordArr[] = strtolower($word);
}
}
}
print_r($output);
Here's a simplified version of the code:
$output = array();
$buzzes = ['instagramm some text instagramm', 'instagramm some text' , 'instagramm some text' , 'instagramm some text'];
foreach( explode( ' ', implode( ' ', $buzzes ) ) as $word )
{
$word = strtolower( trim( $word ) );
if( !empty( $word ) )
{
if( isset( $output[ $word ] ) )
{
$output[ $word ]++;
}
else{ $output[ $word ] = 1; }
}
}
Output:
Array
(
[instagramm] => 5
[some] => 4
[text] => 4
)

Give names to array keys

So I have this code:
<?php
$csv = array();
$lines = file('file.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$csv[$key] = str_getcsv($value);
}
echo '<pre>';
print_r($csv);
echo '</pre>';
?>
which gives me the following
[0] => Array
(
[0] => value1
[1] => value2
[2] => value3
[3] => value4
How can I name my keys? so I don't see 0-1-2-3 but Name1-Name2-Name3 etc.
Like This:
[0] => Array
(
[Name0] => value1
[Name1] => value2
[Name2] => value3
[Name3] => value4
function csvToArray($filename, $delimiter = ',') {
if (!file_exists($filename) || !is_readable($filename)) {
return FALSE;
}
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE) {
if (count($row) > 0 && !is_null($row[0])) {
if (!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}
}
fclose($handle);
}
return $data;
}
Try this function
$filename is the full path to the file
also add in csv as first line keys you want to have and function will use this first line for keys
csv example:
"id","country","city"
"1","us","abanda"
"2","us","abbeville"
Now I understand!
All you need to do in this case is concatenate a string literal onto the front of the key that you generate, like this :-
<?php
$csv = array();
$lines = file('file.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$csv['Name'.$key] = str_getcsv($value);
}
echo '<pre>';
print_r($csv);
echo '</pre>';
?>
$keys = ['Name1', 'Name2', 'Name3', 'etc'];
$csv[$key] = array_combine($keys, str_getcsv($value));
This worked
Thanks Mark Baker

Parse Unserialized array

i have a unserialized array
like this
Array (
[status] => 1
[msg] => Transaction Fetched Successfully
[transaction_details] => Array (
[100002982] => Array (
[mihpayid] => 4149968
[request_id] => 635788
[bank_ref_num] => NINETE.31845.28052012
[amt] => 3295.00
[disc] => 0.00
[mode] => CC
[retries] => 0
[status] => success
[unmappedstatus] => captured
)
)
)
i want to parse this array
so that i can get the value to status ie Success
how i can do that
$success = $array['transaction_details']['100002982']['status'];
$arr['transaction_details']['100002982']['status']
The PHP documentation has a user comment which suggests a method to parse the output of print_r (similar to the above). It can be found here: http://www.php.net/manual/en/function.print-r.php#93529
Here is a copy of the source code found at the above link:
<?php
function print_r_reverse($in) {
$lines = explode("\n", trim($in));
if (trim($lines[0]) != 'Array') {
// bottomed out to something that isn't an array
return $in;
} else {
// this is an array, lets parse it
if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
$spaces = $match[1];
$spaces_length = strlen($spaces);
$lines_total = count($lines);
for ($i = 0; $i < $lines_total; $i++) {
if (substr($lines[$i], 0, $spaces_length) == $spaces) {
$lines[$i] = substr($lines[$i], $spaces_length);
}
}
}
array_shift($lines); // Array
array_shift($lines); // (
array_pop($lines); // )
$in = implode("\n", $lines);
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
$pos = array();
$previous_key = '';
$in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
foreach ($matches as $match) {
$key = $match[1][0];
$start = $match[0][1] + strlen($match[0][0]);
$pos[$key] = array($start, $in_length);
if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
$previous_key = $key;
}
$ret = array();
foreach ($pos as $key => $where) {
// recursively see if the parsed out value is an array too
$ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
}
return $ret;
}
}
?>
I have not tested the above function.

create associative array from array

How can I transform
Array1
(
[0] => Some Text
[1] => Some Other Text (+£14.20)
[2] => Text Text (+£26.88)
[3] => Another One (+£68.04)
)
Into associative array like the one below:
Array2
(
[Some Text] => 0 //0 since there is no (+£val) part
[Some Other Text] => 14.20
[Text Text] => Text Text 26.88
[Another One] => 68.04
)
$newArray = array();
foreach( $oldArray as $str ) {
if( preg_match( '/^(.+)\s\(\+£([\d\.]+)\)$/', $str, $matches ) ) {
$newArray[ $matches[1] ] = (double)$matches[2];
} else {
$newArray[ $str ] = 0;
}
}
Something like this should work:
$a2 = array();
foreach ($Array1 as $a1) {
if (strpos($a1, '(') > 0) {
$text = substr($a1, 0, strpos($a1, '('));
$value = substr($a1, strpos($a1, '(')+3, strpos($a1, ')')-1);
} else {
$text = $a1;
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);
EDIT:
You can do this using explode method as well:
$a2 = array();
foreach ($Array1 as $a1) {
$a1explode = explode("(", $a1, 2);
$text = $a1explode[0];
if ($a1explode[1]) {
$value = substr($a1explode[1],3);
} else {
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);

Categories