Complex parsing a text file in PHP - php

So I am trying to parse a TXT file which has the following format. Each entry is on a single line.
SAMPLE.TXT
2016-02-24 13:54:23 Local0.Info 172.16.120.4 1 1456311263.500015263 ASD_MX600 urls src=172.16.41.15:62490 dst=144.76.76.148:80 mac=00:1B:0D:63:84:00 user=CN=Smith\John,OU=S-HS,OU=SAcc,DC=abc,DC=org,DC=ab agent='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 seb/2.0 SEBKEY' request: GET http://something.com/theme/image.php/clean/page/1455532301/icon
2016-02-24 13:54:23 Local0.Info 172.16.120.4 1 1456311263.500097075 ASD_MX600 urls src=172.16.41.15:62485 dst=144.76.76.148:80 mac=00:1B:0D:63:84:00 user=CN=Smith\John,OU=S-HS,OU=SAcc,DC=abc,DC=org,DC=ab agent='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 seb/2.0 SEBKEY' request: GET http://somethingelse.com/theme/image.php/clean/core/1455532301/f/pdf-24
I need to do the following:
1. Parse the entire file into an array. //DONE
2. Pick up everything after 1 145... (which will end up in [3] of the array) and parse it further so that I have the following breakdowns.
- urls
- src=172.16.41.15:62490
- dst=144.76.76.148:80
- mac=00:1B:0D:63:84:00
- user=CN=Smith\John,OU=S-HS,OU=SAcc,DC=abc,DC=org,DC=ab
- agent='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 seb/2.0 SEBKEY'
- request: GET
- http://something.com/theme/image.php/clean/page/1455532301/icon
I am having a hard time getting the syntax right for the 2nd parse within the main loop. I get the entire giant section from index 3 [3] and I think I am also using the explode() right to chop it off based on ' ' but then I am lost. How do i get hold of the data as shown above? My code progress so far:
<?php
$txt_file = file_get_contents('C:\sample.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(' ', $data); //chop each row first based on bigger space
//--------------------------
$info[$row]['timestamp'] = $row_data[0];
// $info[$row]['localinfo'] = $row_data[1];
$info[$row]['ip'] = $row_data[2];
$info[$row]['other'] = $row_data[3]; //This is where LONGEST string exists
//--------------------------
$row_data1 = explode(' ', $row_data[3]); //chop index item based on smaller space
$rowd_data2[$row_data1]['urlsflows'] = $row_data1[3];
//display data
// echo 'Row ' . $row . ' TIMESTAMP: ' . $info[$row]['timestamp'] . '<br />';
// echo 'Row ' . $row . ' LOCALINFO: ' . $info[$row]['localinfo'] . '<br />';
// echo 'Row ' . $row . ' IP: ' . $info[$row]['ip'] . '<br />';
//--The line below is where I am lost. Kindly help.
echo $rowd_data2[$row_data1]['urlsflows'];
} //end of for loop
?>

This code works for the input file:
<?php
$rows = explode("\n", file_get_contents('SAMPLE.TXT'));
$result = array();
foreach ($rows as $row) {
if (trim($row) == "") {
continue;
}
$timeMatches = array();
$reTime = "/([0-9-]* [0-9:]*) /";
preg_match($reTime, $row, $timeMatches);
$re = "/src=(.*) dst=(.*) mac=(.*) user=(.*) agent=(.*) request: (.*) (.*)/";
$matches = array();
preg_match($re, $row, $matches);
$result[] = array('time' => $timeMatches[1], 'src' => $matches[1]
, 'dst' => $matches[2], 'mac' => $matches[3]
, 'user' => $matches[4], 'agent' => $matches[5]
, 'method' => $matches[6], 'url' => $matches[7]);
}
var_dump($result);
The output of the var_dump($result) is:
array(2) {
[0]=>
array(8) {
["time"]=>
string(20) "2016-02-24 13:54:23"
["src"]=>
string(18) "172.16.41.15:62490"
["dst"]=>
string(16) "144.76.76.148:80"
["mac"]=>
string(17) "00:1B:0D:63:84:00"
["user"]=>
string(49) "CN=Smith\John,OU=S-HS,OU=SAcc,DC=abc,DC=org,DC=ab"
["agent"]=>
string(76) "'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 seb/2.0 SEBKEY'"
["method"]=>
string(3) "GET"
["url"]=>
string(63) "http://something.com/theme/image.php/clean/page/1455532301/icon"
}
[1]=>
array(8) {
["time"]=>
string(20) "2016-02-24 13:54:23"
["src"]=>
string(18) "172.16.41.15:62485"
["dst"]=>
string(16) "144.76.76.148:80"
["mac"]=>
string(17) "00:1B:0D:63:84:00"
["user"]=>
string(49) "CN=Smith\John,OU=S-HS,OU=SAcc,DC=abc,DC=org,DC=ab"
["agent"]=>
string(76) "'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 seb/2.0 SEBKEY'"
["method"]=>
string(3) "GET"
["url"]=>
string(71) "http://somethingelse.com/theme/image.php/clean/core/1455532301/f/pdf-24"
}
}

I think this should work:
$txt_file = file_get_contents('C:\sample.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
$info = [];
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(' ', $data); //chop each row first based on bigger space
//--------------------------
$info[$row] = [];
list($info[$row]['timestamp'], $info[$row]['ip'],$info[$row]['other'] ) = explode(" ", $row_data[0]);
// $info[$row]['localinfo'] = $row_data[1];
//--------------------------
$row_data1 = explode(' ', $row_data[1]); //chop index item based on smaller space
$rowd_data2[$row_data1]['urlsflows'] = $row_data1[3];
//display data
// echo 'Row ' . $row . ' TIMESTAMP: ' . $info[$row]['timestamp'] . '<br />';
// echo 'Row ' . $row . ' LOCALINFO: ' . $info[$row]['localinfo'] . '<br />';
// echo 'Row ' . $row . ' IP: ' . $info[$row]['ip'] . '<br />';
//--The line below is where I am lost. Kindly help.
echo $rowd_data2[$row_data1]['urlsflows'];
} //end of for loop
?>

<?php
$myfile = fopen("C:\sample.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo $line = fgets($myfile) . "<br>";// you can do the explode and assignment here.
//example
$row_data = explode(' ', $line);
//don't worry about spaces, it will trim by PHP `trim` function, that will erase all the spaces
}
fclose($myfile);
?>

Related

How to parse and get image,description from meta tags for given url?

I tried to get image and other data from meta tags.
Can you please guide me how to get image from particular URL?
E.g. URL :
https://www.myntra.com/casual-shoes/kook-n-keech/kook-n-keech-men-white-sneakers/2154180/buy
2 . https://www.amazon.in/Redmi-Pro-Black-32GB-Storage/dp/B07DJL15QT/ref=lp_16113280031_1_1?srs=16113280031&ie=UTF8&qid=1553411505&sr=8-1
3.https://www.flipkart.com/asian-wndr-13-training-shoes-walking-shoes-gym-shoes-sports-shoes-running-men/p/itmfatksqm2wzfw8?pid=SHOF3KF5XZZHCMBD&lid=LSTSHOF3KF5XZZHCMBDS561HI&marketplace=FLIPKART&spotlightTagId=BestsellerId_osp%2Fcil&srno=b_1_1&otracker=hp_omu_Deals%2Bof%2Bthe%2BDay_2_XI7YOJ4F5LAF_0&otracker1=hp_omu_PINNED_neo%2Fmerchandising_Deals%2Bof%2Bthe%2BDay_NA_dealCard_cc_2_NA_0&fm=neo%2Fmerchandising&iid=11b0262a-d573-4a8d-9938-55051f6474c9.SHOF3KF5XZZHCMBD.SEARCH&ppt=StoreBrowse&ppn=Store&ssid=gvvzlooffk0000001553411768922
Code:
function getUrlData($url) {
$result = false;
$contents = getUrlContents($url);
if (isset($contents) && is_string($contents)) {
$title = null;
$metaTags = null;
preg_match('/<title>([^>]*)<\/title>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) > 0) {
$title = strip_tags($match[1]);
}
preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 3) {
$originals = $match[0];
$names = $match[1];
$values = $match[2];
if (count($originals) == count($names) && count($names) == count($values)) {
$metaTags = array();
for ($i = 0, $limiti = count($names); $i < $limiti; $i++) {
$metaTags[$names[$i]] = array(
'html' => htmlentities($originals[$i]),
'value' => $values[$i]
);
}
}
}
$result = array(
'title' => $title,
'metaTags' => $metaTags
);
}
return $result;
}
function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0) {
$result = false;
$contents = #file_get_contents($url);
// Check if we need to go somewhere else
if (isset($contents) && is_string($contents)) {
preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1) {
if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections) {
return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
}
$result = false;
} else {
$result = $contents;
}
}
return $contents;
}
$test = getUrlData('https://www.amazon.in/Redmi-Pro-Black-32GB-Storage/dp/B07DJL15QT/ref=lp_16113280031_1_1?srs=16113280031&ie=UTF8&qid=1553411505&sr=8-1'); //Replace with your URL
here
echo '<pre>';
print_r($test);
Result From 1st URL : BLANK
Result From 2st URL : 2nd URL
Result From 3rd URL : 3rd URL
i cant find image Data from this URLS and 1st url not working .
Use DomDocument and DOMXPath to parse the html retrieved from given url:
function outputMetaTags($url){
// $url = 'https://www.myntra.com/casual-shoes/kook-n-keech/kook-n-keech-men-white-sneakers/2154180/buy';
$streamContext = stream_context_create(array(
"http" => array(
"header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
'follow_location' => false
)
)
); //we try to act as browser, just in case server forbids us to access to page
$htmlData = file_get_contents($url, false, $streamContext); //fetch the html data from given url
//libxml_use_internal_errors(true); //optionally disable libxml url errors and warnings
$doc = new DOMDocument(); //parse with DOMDocument
$doc->loadHTML($htmlData);
$xpath = new DOMXPath($doc); //create DOMXPath object and parse loaded DOM from HTML
$query = '//*/meta';
$metaData = $xpath->query($query);
foreach ($metaData as $singleMeta) {
//for og:image, check if $singleMeta->getAttribute('property') === 'og:image', same goes with og:url
//not every meta has property or name attribute
if(!empty($singleMeta->getAttribute('property'))){
echo $singleMeta->getAttribute('property') . "\n";
}elseif(!empty($singleMeta->getAttribute('name'))){
echo $singleMeta->getAttribute('name') . "\n";
}
//get content from meta tag
echo $singleMeta->getAttribute('content') . "\n";
}
}
See more about DOMDocument and DOMXpath:
http://php.net/manual/en/class.domdocument.php
http://php.net/manual/en/class.domxpath.php
About meta tags:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta

How to separate mp3, mp4 file name from string using php?

Hi anyone can help I want separate mp3, mp4 from imploded data in PHP
my data string
$data = "song1.mp3, video1.mp4, song2.mp3"
i want to divide into two separate strings 1 string contains only mp4 with (,) separated and another with mp3
my data from database:
$data = "song1.mp3, video.mp4, song2.mp3";
$mp4 = video1.mp4,video2.mp4,..etc;
$mp3 = song1.mp3,song2.mp3,..etc;
thank you
Assuming your songs names are well formatted, meaning that they are named as title.suffix
<?php
$data = "song1.mp3, video.mp4, song2.mp3";
$mp3 = [];
$mp4 = [];
$song_names = explode(',', $data);
foreach ($song_names as $song_name) {
$song_name = trim($song_name);
$parts = explode('.', $song_name);
if (count($parts) == 2) {
$suffix = $parts[1];
if ($suffix == 'mp3') {
$mp3[] = $song_name;
} else if ($suffix == 'mp4') {
$mp4[] = $song_name;
}
}
}
//using implode so that we won't have an extra comma hanging in the end
$mp4 = implode(', ', $mp4);
$mp3 = implode(', ', $mp3);
?>
Use explode() to converting string to array by , delimiter. Then loop through array items and get extension of file name using substr() and check it.
$data = "song1.mp3, video1.mp4, song2.mp3";
$mp4 = $mp3 = "";
foreach (explode(",", $data) as $file){
$file = trim($file);
substr($file, -3) == "mp4" ? $mp4.=$file."," : $mp3.=$file.",";
}
$mp4 = substr($mp4, 0, -1);
$mp3 = substr($mp3, 0, -1);
Check result in demo
This sounds like a job for a preg_match_all() regex:
<?php
$string = 'song1.mp3, video.mp4, song2.mp3';
$regex = '#([^,\s]+\.mp3)#';
preg_match_all($regex, $string, $mp3s);
$regex = '#([^,\s]+\.mp4)#';
preg_match_all($regex, $string, $mp4s);
var_dump($mp3s[0]);
var_dump($mp4s[0]);
Which gives you:
array(2) { [0]=> string(9) "song1.mp3" [1]=> string(9) "song2.mp3" }
array(1) { [0]=> string(9) "video.mp4" }
Here's the code in action https://3v4l.org/2EmkR
Here's the docs for preg_match_all() http://php.net/manual/en/function.preg-match-all.php
Ok - a slightly different approach using pathinfo
$data = 'song1.mp3, video1.mp4, song2.mp3';
$mp3s = [];
$mp4s = [];
foreach (explode(', ', $data) as $file) {
$type = pathinfo($file)['extension'];
$type === 'mp3' ? $mp3s[] = $file : $mp4s[] = $file;
}
echo implode(', ', $mp4s) . PHP_EOL;
echo implode(', ', $mp3s) . PHP_EOL;
Could definitely use some validation and so forth but as an MVP it does the trick.

Match variable value with text file row wise

I want to match variable value with text file rows, for example
$brands = 'Applica';
and text file content like -
'applica' = 'Applica','Black and Decker','George Foreman'
'black and decker' = 'Black and Decker','Applica'
'amana' = 'Amana','Whirlpool','Roper','Maytag','Kenmore','Kitchenaid','Jennair'
'bosch' = 'Bosch','Thermador'
As there are four rows in text file.
and first word of each row is brand which is compatible with their equal to brands.
like applica is compatible with 'Applica' and 'Black and Decker' and 'George Foreman'
I want to match variable $brands with word applica and if it matches then store their equal to value like 'Applica','Black and Decker','George Foreman' in new variable.
Please provide some guidance.
Thanks.
Update -
<?php
$brands = "brands.txt";
$contents = file_get_contents($brands);
$brandsfields = explode(',', $contents);
$csvbrand = 'applica';
foreach($brandsfields as $brand) {
$newname = substr($brand,1,-1);
echo $newname . "\t";
}
?>
This should work
$matches = explode("\n", "'applica' = 'Applica','Black and Decker','George Foreman'\n'black and decker' = 'Black and Decker','Applica'\n'amana' = 'Amana','Whirlpool','Roper','Maytag','Kenmore','Kitchenaid','Jennair'\n'bosch' = 'Bosch','Thermador'");
$brand = "applica";
$equalValues = [];
foreach ($matches as $key => $value) {
$keyMatch = str_replace("'", "", trim(explode('=', $value)[0]));
$valuesMatch = explode('=', $value)[1];
$escapedDelimiter = preg_quote("'", '/');
preg_match_all('/' . "'" . '(.*?)' . "'" . '/s', $valuesMatch, $matches);
if ($brand == $keyMatch) {
$equalValues = $matches[1];
}
}
var_dump($equalValues);
if brand is equal to applica $equalvalues shoud be equal to :
array(3) {
[0]=>
string(7) "Applica"
[1]=>
string(16) "Black and Decker"
[2]=>
string(14) "George Foreman"
}
preg_match_all("/'" . $csvbrand ."' = (.*)/", $contents, $output_array);
$names = explode(",", str_replace("'", "", $output_array[1][0]));
Var_dump($names); // results in ->
//Applica
//Black and Decker
//George Foreman

Q: How can I combine these two foreach loop

I have a simple html dom query which read informations from a football fixtures source, and I loading also a json source.
Here is my full code:
<?php
header('Content-Type: text/html; charset=utf-8');
ini_set("user_agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17");
include_once('simple_html_dom.php');
ini_set('display_errors', true);
error_reporting(E_ALL);
$str = file_get_contents('general.json');
$json = json_decode($str,true);
$filename = "source.html";
$html = file_get_html($filename);
class matches {
var $day;
var $kickofftime;
var $result;
function matches ($day, $kickofftime, $tip){
$this->day=$day;
$this->kickofftime=$kickofftime;
$this->result=$result;
return $this;
}
}
$i=0;
$day=$html->find('h1',0);
$day->plaintext;
$day=str_replace("<h1>TODAY FOOTBALL FIXTURES: ","", $day);
$day=str_replace("</h1>","", $day);
$matchday = str_replace(array('MONDAY ', 'TUESDAY ', 'WEDNESDAY ', 'THURSDAY ', 'FRIDAY ', 'SATURDAY ', 'SUNDAY '), '', $day);
$matchday=str_replace(" ","-", $matchday);
$matchday=date('Y-m-d', strtotime($matchday));
foreach($html->find('table.fixtures') as $matches)
{
foreach ($matches->find('tr[class=a1],tr[class=a2]') as $matchesTR) {
$kickofftime=$matchesTR->find('td[class=a11],td[class=a21]',0)->plaintext;
$kodate = date('Y-m-d H:i:s', strtotime("$matchday $kickofftime +1 hour"));
$result=$matchesTR->find('td');
echo $kodate;
echo $result[6]->plaintext.'<br>' ;
$i++;
}
}
//Here is the 2nd foreach with the data of JSON source:
foreach($json as $key => $value) {
$value = json_decode($value, true);
echo $value["country"] . ", " . $value["competition"] . " " . $value["club"] . "<br>";
}
// clean up memory
$html->clear();
unset($html);
?>
The current results from the simple html dom html source:
2014-12-23 20:00:00 2-1
2014-12-23 11:00:00 3-1
2014-12-26 08:00:00 1-1
The result from the JSON source:
America Copa America Boca Juniors
Europe Bundesliga Hannover
Asia JLeague Nagoya
I would like to combine these two results in one foreach and I would like to get this result:
2014-12-23 20:00:00 2-1 America Copa America Boca Juniors
2014-12-23 11:00:00 3-1 Europe Bundesliga Hannover
2014-12-26 08:00:00 1-1 Asia JLeague Nagoya
I hope that there is some expert who can help for me because I tried a lot of variation but without result. I got some advice (with code) from experts, but there was everytime errors. With my code there is no error, but I need other solution because I would like to put all variables to one foreach. Many thanks, I hope that somebody could help me with code, because I am not on high level at php. Thanks again!
I would like to put the two foreach into one foreach, but I don't want to create a new array because I not need.
Assuming you will always have the same amount of items in each and that they match 1 to 1, 2 to 2, you can do this:
$htmlDates = array();
$jsonLeag = array();
foreach($html->find('table.fixtures') as $matches) {
foreach($matches->find('tr[class=a1],tr[class=a2]') as $matchesTR) {
$kickofftime=$matchesTR->find('td[class=a11],td[class=a21]',0)->plaintext;
$kodate = date('Y-m-d H:i:s', strtotime("$matchday $kickofftime +1 hour"));
$result=$matchesTR->find('td');
//echo $kodate;
//echo $result[6]->plaintext.'<br>' ;
$htmlDates[] = $kodates;
}
}
//Here is the 2nd foreach with the data of JSON source:
foreach($json as $key => $value) {
$value = json_decode($value, true);
//echo $value["country"] . ", " . $value["competition"] . " " . $value["club"] . "<br>";
$jsonLeag[] = $value["country"] . ", " . $value["competition"] . " " . $value["club"];
}
if(count($htmlDates) < count($jsonLeag)){
for($i=0;$i<count($htmlData);$i++){
echo $htmlData[$i] . " " . $jsonLeag[$i] . "<br />\r\n";
}
} else {
for($i=0;$i<count($jsonLeag);$i++){
echo $htmlData[$i] . " " . $jsonLeag[$i] . "<br />\r\n";
}
}
Since you have the nested list first and nothing ties the two data sets together, there is no simple way to run one loop and get the data from both. It's easier to push the data you want into an array for each set, and then walk both arrays with one counter. The caveat here is that if one has an extra element, you will get missing results or errors.
Save keys of json arrays and use the next in each loop.
$json_keys = array_keys($json);
$i_key = 0;
foreach($html->find('table.fixtures') as $matches)
{
foreach ($matches->find('tr[class=a1],tr[class=a2]') as $matchesTR) {
$kickofftime=$matchesTR->find('td[class=a11],td[class=a21]',0)->plaintext;
$kodate = date('Y-m-d H:i:s', strtotime("$matchday $kickofftime +1 hour"));
$result=$matchesTR->find('td');
echo $kodate;
echo $result[6]->plaintext.
$value = json_decode($json[$json_keys[$i_key++]], true);
echo $value["country"] . ", " . $value["competition"] . " " . $value["club"] . "<br>";
$i++;
}
}
// clean up memory
$html->clear();
unset($html);
There are many other variants - use array_shift(), next()... I've written the first come in mind

Use PHP implode + array to return a comma separated list?

I working on some WordPress code with the WP Alchemy class, and I'm trying to recall the meta values used in a page template as a comma separated list. However when WP Alchemy Meta Boxes store the values into the domain, they aren't saved with delimiters nor spaces, so it's much like: onetwothreefourfive...
Here's what I have so far:
<?php $meta = get_post_meta(get_the_ID(), $custom_metabox->get_the_id(), TRUE); ?>
<li>Via: <?php foreach ($meta['g2m_via'] as $link) { ?><a href="<?php echo $link['g2m_via-link']; ?>">
<?php
$prefix = ', ';
$words = array();
$words[] = $link['g2m_via-title'];
$words = array_map("unserialize", array_unique(array_map("serialize", $words)));
for($i = 0; $i < count($words); $i++){ $fruitlist = implode(', ', $words); print_r($fruitlist); }
?></a><?php } ?></li>
$link['g2m_via-title'] is simply the name of the link that is stored in the meta field, i.e. Link1 would be the name, google,,com would be the link (which is not important here, I have that working). The other variables are all there. The $prefix variable does nothing, it was meant to act as a separator, like: $val .= $prefix . '' $link['g2m_via-title']; . ''; however, it causes: Link1, Link 1,Link 2, Link 1, Link 2, Link 3.
So far with that code, I've gotten the closest to what I want:
Link1Link2Link3
But it needs to be: Link1, Link2, Link3, and so on without the comma on the last link title.
Output of var_dump($link):
array(2) {
["g2m_via-title"]=> string(7) "JoyStiq"
["g2m_via-link"]=> string(22) "joystiq.com";
}JoyStiq
array(2) {
["g2m_via-title"]=> string(9) "GrindGadget"
["g2m_via-link"]=> string(16) "grindgadget.com";
} GrindGadget
array(2) {
["g2m_via-title"]=> string(13) "Engadget"
["g2m_via-link"]=> string(13) "engadget.com";
} Engadget
What I WANT it to look like so ["g2m_via-title"] will stop duplicating:
array[1] {
["g2m_via-title"]=> "JoyStiq"
["g2m_via-link"]=> "joystiq.com";
}
array[2] {
["g2m_via-title"]=> "GrindGadget"
["g2m_via-link"]=> "grindgadget.com";
}
array[3] {
["g2m_via-title"]=> "Engadget"
["g2m_via-link"]=> "engadget.com";
}
3 of the countless other pieces of code that I've tried: http://pastebin.com/wa0R8sDw.
Assuming this data structure:
$links = array(
array(
"g2m_via-title" => "JoyStiq",
"g2m_via-link" => "joystiq.com"
),
array(
"g2m_via-title" => "GrindGadget",
"g2m_via-link" => "grindgadget.com"
),
array(
"g2m_via-title" => "Engadget",
"g2m_via-link" => "engadget.com"
)
);
This'll do:
$output = array();
foreach ($links as $link) {
$output[] = sprintf('%s',
$link['g2m_via-link'],
htmlentities($link['g2m_via-title']));
}
echo join(', ', $output);
So will this in PHP 5.3+:
echo join(', ', array_map(function ($link) {
return sprintf('%s',
$link['g2m_via-link'],
htmlentities($link['g2m_via-title']));
}, $links));

Categories