I have a return string from a 3rd party plugin that looks like a var_dump from an array. I'm trying to parse into a valid associative array. Looking at various examples and doing some tests with the code that follows. The last segment demonstrates the problem I'm having. I'm trying to parse out the data into a string and then programmatically create an array after my data string has been finished. When I do a print_r on $vegetables2, I get:
Array([0] => “Gourd”=”40 kilojoules”,”Artichoke”=”105 kilojoules”,”Cassava”=”550 kilojoules”)
And the echo $vegetables2["Artichoke"] produces no value. Can someone please guide me at the correct syntax to create the array equivalent to the first two examples?
//this works:
echo "From creating the entire array with a static string:<br/>";
$vegetables = array("Gourd"=>"40 kilojoules", "Artichoke"=>"105 kilojoules", "Cassava"=>"550 kilojoules");
echo "Artichoke: " . $vegetables["Artichoke"] . "<br/>";
//this works too
$vegetables1['Gourd'] = "40 kilojoules";
$vegetables1['Artichoke'] = "105 kilojoules";
$vegetables1['Cassava'] = "550 kilojoules";
echo "From creating one element at a time:<br/>";
echo "Artichoke: " . $vegetables1["Artichoke"] . "<br/>";
//this doesn't work
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
echo $strData ."<br/>";
$vegetables2 = array($strData);
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
$dd=str_replace('"','',"$strData");
$ff=explode(',',$dd);
foreach ($ff as $c)
{
$xx=explode('=',$c);
$vegetables2["$xx[0]"]=$xx[1];
}
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
This string is your input:
"Array ( [Gourd] => 40 kilojoules [Artichoke] => 105 kilojoules [Casava] => 550 kilojoules )"
use strpos() to locate "("
use strpos() to locate ")"
use substr() to get what is between ( and )
use explode to divide the result wherever "[" appears
use array() to start a new array
use foreach to reformat each piece
use explode to divide each piece wherever "=>" appears
use trim to remove excess characters (left and right)
use $data[$key] = $value to create a new array to your liking
Related
The code below is working in reading per row and count each identical appearances. However, I still need excel to sort per row left to right before I i save it as delimited by as text file. Right now I want to omit the excel step. I checked on php manual and saw the sort and explode functions. I inserted those command but its not working. Can someone help me point to the right direction ?
raw data is :
hero2,hero1,hero3
hero2,hero3,hero4
hero1,hero2,hero3
text file db after excel :
hero1,hero2,hero3
hero2,hero3,hero4
hero1,hero2,hero3
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
Code :
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sort ($lines);
$result = array_count_values($lines);
foreach($result as $v => $amount)
echo "Appeared " . $amount . "x: " . $v . "<br />";
?>
After reading the suggestions and samples of those who answered I came up with this code now.
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", implode($data));
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "\n";
}
?>
however the ouput became like this
output :
appeared 3x: hero2
appeared 3x: hero3
appeared 2x: hero1
appeared 1x: hero4
correct output should be like this
output :
appeared 2x: hero1,hero2,hero3
apprered 1x: hero2,hero3,hero4
I believe your problem is you are using explode with a space and you should be using it with a comma. explode(",",$data);
I'm thinking you then also want to turn your data back into a string before you try and count them or I don't think you'll get the results you're expecting.
For example...
$sortedString = implode(",", $theArray);
You are looping over the old data before doing the sort. And you are not using a PHP function sort, you are instead making it a kind of a variable (remove the $ before it).
<?php
$data = file("heroes.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = explode(",", $data);
$sorted_lines = sort($lines); // sorted data
$result = array_count_values($sorted_lines);
// output the sorted data
foreach($result as $v => $amount) {
echo "Appeared " . $amount . "x: " . $v . "<br />";
}
?>
I Have an Array that I want a foreach to display the Key and Value as XML. The Page is coming up with <$value> and that is it? Any Ideas? Thank You!
$XML_a = array ("Ticket_ID" => "12343456");
$query = "";
$string_top =
"<varcor_api>
<response>";
foreach ($XML_a as $key => $value) {
$query .= "<" . $key . "><" . $value . "></" . $key . ">";
}
$string_bottom = "
</response>
</varcor_api>
";
echo $string_top . $query . $string_bottom;
It's bad idea to concatenate XML strings into XML structure. Instead, use Array to XML conversion algorithm - see Convert array to XML and How to convert array to SimpleXML.
Hi I have this array called $allextensionsforque. See print_r below.
Array ( [0] => Local/101#from-queue/n,0 [data] => Local/101#from-queue/n,0 )
I'm trying a foreach like below but its not showing any data on the echo. Can anyone help?
$allextensionsforqueu = mysqli_query($conqueue,"SELECT data FROM queues_details WHERE id = '1' AND keyword ='member'");
$allextensionsforque = mysqli_fetch_array($allextensionsforqueu);
$foo = "";
foreach ($allextensionsforque as $extensionrow)
{
$extensionrowstriped = substr($extensionrow['data'],6,3);
$foo = "' " . $extensionrowstriped . " ' ,";
}
echo $foo;
You don't have an array in $extensionrow, since it's only an one dimensional array. So you just need to replace $extensionrowstriped = substr($extensionrow['data'],6,3); with $extensionrowstriped = substr($extensionrow,6,3);.
Check for errors using mysqli_error(). Here is a simple approach, but you may want to improve it for production use:
$allextensionsforqueu = mysqli_query($conqueue,"...") or die(mysqli_error($conqueue));
Next, append your data to $foo instead of overwritting it in each loop:
$foo .= "' " . $extensionrowstriped . " ' ,";
Finally, verify that $extensionrow contains the data that you expect. substr() will return false if a match is not found.
I've been searching and searching and can't find anything that works, but this is what I want to do.
This code:
try{
$timeout = 2;
$scraper = new udptscraper($timeout);
$ret = $scraper->scrape('udp://tracker.openbittorrent.com:80',array('0D7EA7F06E07F56780D733F18F46DDBB826DCB65'));
print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
Outputs this:
Array ( [0D7EA7F06E07F56780D733F18F46DDBB826DCB65] => Array ( [seeders] => 148 [completed] => 10 [leechers] => 20 [infohash] => 0D7EA7F06E07F56780D733F18F46DDBB826DCB65 ) )
And I want that seeder count into a string such as $seeds. How would I go about doing this?
Something like this?
$seeds = $ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders'];
you can user strval() to convert a number to a string.
$string = strval($number);
or you can cast it into a string:
$string = (string)$number;
in your context that would be:
$string = strval($ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders']);
However that odd string is also the first index of the array so you could also do it like this:
$string = strval($ret[0]['seeders']);
or if you want ot use only indexes ('seeders' is also the first index of the second array):
$string = strval($ret[0][0]);
if you just want the number then it's easy too:
$num = $ret[0][0];
It's not clear if you're looking to assign the array value(s?) as a separate variable(s?) or just to cast it into a string. Here's a nice way to accomplish all the above options, by assigning each array key as a separate variable with the matching array value:
$ret_vars = array_pop($ret);
foreach ($ret_vars as $variable_name=>$variable_value) :
${$variable_name} = (string)$variable_value;
endforeach;
In your original example, this would end up populating $seeders, $completed, $leechers and $infohash with their matching string values. Of course, make sure these variable names are not used/needed elsewhere in the code. If that's the case, simply add some sort of unique prefix to the ${} construct, like ${'ret_'.$variable_name}
So I'm cycling through a document with 41 paragraphs. For each paragraph I'm trying to [1] first break the string into an array, and then get the word frequency of the paragraph. I then want to combine the data from all paragraphs and get the word frequency of the whole document.
I'm able to get array that gives me the "word" and its "frequency" for a given pargraph but I'm having trouble merging the results from each paragraph so as to get the "word frequency of the whole document. Here is what I have:
function sectionWordFrequency($sectionFS)
{
$section_frequency = array();
$filename = $sectionFS . ".xml";
$xmldoc = simplexml_load_file('../../editedtranscriptions/' . $filename);
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$paraArray = $xmldoc->xpath("//tei:p");
foreach ($paraArray as $p)
{
$para_frequency = (array_count_values(str_word_count(strtolower($p), 1)));
$section_frequency[] = $para_frequency;
}
return array_merge($section_frequency);
}
/// now I call the function, sort it, and try to display it
$section_frequency = sectionWordFrequency($fs);
ksort($section_frequency);
foreach ($section_frequency as $word=>$frequency)
{
echo $word . ": " . $frequency . "</br>";
}
Right now the result I get is:
1: Array
2: Array
3: Array
4: Array
Any help is greatly appreciated.
Try to replace this line
$section_frequency[] = $para_frequency;
with this
$section_frequency = array_merge($section_frequency, $para_frequency);
and then
return $section_frequency