Using foreach in conjunction with a multi-dimensional array(?) - php

I am trying to use Simple HTML DOM to cycle through an HTML file and find all HREF links that contain the string "/en/news/". For each of these values in this initial array, I want to give certain attributes as seen below.
foreach($html->find('a[href^="/en/news/"]') as &$a) {
$arrayz = array(
'hyperLink' => 'http://samplewebsite.com' . $a->href,
'fileName' => str_replace("-", "", filter_var($a, FILTER_SANITIZE_NUMBER_INT)) . ".txt",
'processedTime' => date_default_timezone_get()
);
}
echo '<pre>', print_r($arrayz), '</pre>';
However, this is only printing the hyperLink, filename, and processedTime values for a SINGLE member of the initial array.
How can I make this work for all members of the initial array?
Thanks!

You are overwriting a single array inside the loop, try this:
foreach($html->find('a[href^="/en/news/"]') as &$a) {
$arrayz[] = array(
'hyperLink' => 'http://samplewebsite.com' . $a->href,
'fileName' => str_replace("-", "", filter_var($a, FILTER_SANITIZE_NUMBER_INT)) . ".txt",
'processedTime' => date_default_timezone_get()
);
}
echo '<pre>', print_r($arrayz), '</pre>';

Related

PHP - Implode, Explode works sometimes, and sometimes not? [duplicate]

What is the best way that I can pass an array as a url parameter? I was thinking if this is possible:
$aValues = array();
$url = 'http://www.example.com?aParam='.$aValues;
or how about this:
$url = 'http://www.example.com?aParam[]='.$aValues;
Ive read examples, but I find it messy:
$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';
There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:
$data = array(
1,
4,
'a' => 'b',
'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));
will return
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.
Edit: Don't miss Stefan's solution above, which uses the very handy http_build_query() function: https://stackoverflow.com/a/1764199/179125
knittl is right on about escaping. However, there's a simpler way to do this:
$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&aValues[]=', array_map('urlencode', $aValues));
If you want to do this with an associative array, try this instead:
PHP 5.3+ (lambda function)
$url = 'http://example.com/index.php?';
$url .= implode('&', array_map(function($key, $val) {
return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
},
array_keys($aValues), $aValues)
);
PHP <5.3 (callback)
function urlify($key, $val) {
return 'aValues[' . urlencode($key) . ']=' . urlencode($val);
}
$url = 'http://example.com/index.php?';
$url .= implode('&', array_map('urlify', array_keys($aValues), $aValues));
Easiest way would be to use the serialize function.
It serializes any variable for storage or transfer. You can read about it in the php manual - serialize
The variable can be restored by using unserialize
So in the passing to the URL you use:
$url = urlencode(serialize($array))
and to restore the variable you use
$var = unserialize(urldecode($_GET['array']))
Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.
Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.
please escape your variables when outputting (urlencode).
and you can’t just print an array, you have to build your url using a loop in some way
$url = 'http://example.com/index.php?'
$first = true;
foreach($aValues as $key => $value) {
if(!$first) $url .= '&amp';
else $first = false;
$url .= 'aValues['.urlencode($key).']='.urlencode($value);
}
<?php
$array["a"] = "Thusitha";
$array["b"] = "Sumanadasa";
$array["c"] = "Lakmal";
$array["d"] = "Nanayakkara";
$str = serialize($array);
$strenc = urlencode($str);
print $str . "\n";
print $strenc . "\n";
?>
print $str . "\n";
gives a:4:{s:1:"a";s:8:"Thusitha";s:1:"b";s:10:"Sumanadasa";s:1:"c";s:6:"Lakmal";s:1:"d";s:11:"Nanayakkara";}
and
print $strenc . "\n"; gives
a%3A4%3A%7Bs%3A1%3A%22a%22%3Bs%3A8%3A%22Thusitha%22%3Bs%3A1%3A%22b%22%3Bs%3A10%3A%22Sumanadasa%22%3Bs%3A1%3A%22c%22%3Bs%3A6%3A%22Lakmal%22%3Bs%3A1%3A%22d%22%3Bs%3A11%3A%22Nanayakkara%22%3B%7D
So if you want to pass this $array through URL to page_no_2.php,
ex:-
$url ='http://page_no_2.php?data=".$strenc."';
To return back to the original array, it needs to be urldecode(), then unserialize(), like this in page_no_2.php:
<?php
$strenc2= $_GET['data'];
$arr = unserialize(urldecode($strenc2));
var_dump($arr);
?>
gives
array(4) {
["a"]=>
string(8) "Thusitha"
["b"]=>
string(10) "Sumanadasa"
["c"]=>
string(6) "Lakmal"
["d"]=>
string(11) "Nanayakkara"
}
again :D
I do this with serialized data base64 encoded. Best and smallest way, i guess. urlencode is to much wasting space and you have only 4k.
why: http://mizine.de/html/array-ueber-get-url-parameter-uebergeben/
how: https://gist.github.com/vdite/79919fa33a3e4fbf505c
This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.
I will repeat this bit
$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);
Obviously you would format it better than this
www.someurl.com?x=$query
And to get the data back
parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];
**in create url page**
$data = array(
'car' => 'Suzuki',
'Model' => '1976'
);
$query = http_build_query(array('myArray' => $data));
$url=urlencode($query);
echo" <p> Send <br /> </p>";
**in received page**
parse_str($_GET['data']);
echo $myArray['car'];
echo '<br/>';
echo $myArray['model'];
in the received page you can use:
parse_str($str, $array);
var_dump($array);
You can combine urlencoded with json_encode
Exemple:
<?php
$cars = array
(
[0] => array
(
[color] => "red",
[name] => "mustang",
[years] => 1969
),
[1] => array
(
[color] => "gray",
[name] => "audi TT",
[years] => 1998
)
)
echo "<img src='your_api_url.php?cars=" . urlencode(json_encode($cars)) . "'/>"
?>
Good luck ! 🐘
Very easy to send an array as a parameter.
User serialize function as explained below
$url = www.example.com
$array = array("a" => 1, "b" => 2, "c" => 3);
To send array as a parameter
$url?array=urlencode(serialize($array));
To get parameter in the function or other side use unserialize
$param = unserialize(urldecode($_GET['array']));
echo '<pre>';
print_r($param);
echo '</pre>';
Array
(
[a] => 1
[b] => 2
[c] => 3
)

Getting extra slashes while using JSON array in PHP

I am getting some extra slashes while making json array using PHP. My code is below.
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001","subject"=>"Mathematics"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002","subject"=>"History"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001","subject"=>"Geology"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA003","subject"=>"Science"));
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'reg_no' => $value['reg_no'],
'name' => $name,
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'].'/'.$value['subject'];
}
$result = array_values($result); // reindex result array
echo json_encode($result);exit;
?>
Here the json output is given below.
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001\/Mathematics","paper2":"BA002\/History","paper3":"BA003\/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001\/Geology","paper2":"","paper3":"","paper4":""}]
Here my problem is I am adding $value['paper_code'].'/'.$value['subject']; and in output I am getting "BA001\/Mathematics". Here One extra slash(\) is added which I need to remove.
You can add JSON_UNESCAPED_SLASHES as the second parameter. LIke:
$result = array_values($result); // reindex result array
echo json_encode($result,JSON_UNESCAPED_SLASHES);exit;
This will result to:
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001/Mathematics","paper2":"BA002/History","paper3":"BA003/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001/Geology","paper2":"","paper3":"","paper4":""}]
Doc: json_encode()

Dynamically update a php array with a function

I have multiple sitemaps and I would like to merge them all, but before merging them, I need to append a unique variable to all values in all arrays.
// The global variable
define("BASE_URL", "http://domain.com");
$sitemap_full = [ "home" => BASE_URL ];
// One of the arrays
$sitemap_example = [
"foo" => "/bar",
"gnu" => "/lar"
];
Since I have multiple of those arrays, I wanted to create a function that will append the link.
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
return $sitemap[$title] = BASE_URL . $url;
}
}
And in action in will be:
pushToSitemap($sitemap_example, $sitemap_full);
But this just doesn't work because if I print_r($sitemap_full); it will display Array( "home", "http://domain.com" );.
What really annoys me is that if in the function I echo them, they will be echoed.
What am I doing wrong?
EDIT
It should display
Array(
"home" => "http://domain.com"m
"foo" => "http://domain.com/bar",
"gnu" => "http://domain.com/lar
);
Your problem seems lie inside your foreach function:
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
return $sitemap[$title] = BASE_URL . $url;
}
}
You are returning just a single item, what's more, the formatting is off.
Instead,
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
$sitemap[$title] = BASE_URL . $url;
}
return $sitemap;
}
$sitemap_full = pushToSitemap($sitemap_example, $sitemap_full);

PHP adding foreach to my array

I would like to append html to an item in my array before echoing it on my page and am unsure how to go about doing it.
My data is put into an array like so:
$query = $this->db->get();
foreach ($query->result() as $row) {
$data = array(
'seo_title' => $row->seo_title,
'seo_description' => $row->seo_description,
'seo_keywords' => $row->seo_keywords,
'category' => $row->category,
'title' => $row->title,
'intro' => $row->intro,
'content' => $row->content,
'tags' => $row->tags
);
}
return $data;
I would like to perform the following on my 'tags' before returning the data to my view:
$all_tags = explode( ',' , $row->tags );
foreach ( $all_tags as $one_tag ){
echo '' . $one_tag . '';
The reason for doing this is that the tags in my database contain no html and are simply separated by commas like so news,latest,sports and I want to convert them into
sports ...
My reason for doing this here rather than when I echo the data is that I don't want to repeat myself on every page.
You could just create a function to be used everyhwere you are including tags in your output:
function formatTags($tags) {
$tmp = explode(',', $tags);
$result = "";
foreach ($tmp as $t) {
$result .= sprintf('%s',
urlencode(trim($t)), htmlentities(trim($t)));
}
return $result;
}
And whenever you do something like echo $tags; you do echo formatTags($tags); instead. View code should be separated from model code, which is why I would advise to not put HTML inside your array.
Well first of all you're overwriting $data with every run of the loop so only the final result row will be listed.
Once that's out of the way (fix with $data[] = ...), try this:
...
'tags' => preg_replace( "/(?:^|,)([^,]+)/", "$1", $row->tags);
...

Using foreach inside of a defined array PHP

Is there anyway to loop through an array and insert each instance into another array?
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
foreach($aCartInfo['items'] as $item){
'x_line_item' => $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|>N',
}
);
Not directly in the array declaration, but you could do the following:
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(),
);
foreach($aCartInfo['items'] as $item){
$aFormData['x_line_item'][] = $item['id'].'<|>'.$item['title'].'<|>'.$item['description'].'<|>'.$item['quantity'].'<|>'.$item['price'].'<|>N';
}
Yes, there is a way ; but you must go in two steps :
First, create your array with the static data
And, then, dynamically add more data
In your case, you'd use something like this, I suppose :
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(), // right now, initialize this item to an empty array
);
foreach($aCartInfo['items'] as $item){
// Add the dynamic value based on the current item
// at the end of $aFormData['x_line_item']
$aFormData['x_line_item'][] = $item['id'] . '<|>' . $item['title'] . '<|>' . $item['description'] . '<|>' . $item['quantity'] . '<|>' . $item['price'] . '<|>N';
}
And, of course, you should read the section of the manual that deals with arrays : it'll probably help you a lot ;-)
You mean something like this :
$aFormData = array(
'x_show_form' => 'PAYMENT_FORM',
'x_line_item' => array(),
);
foreach($aCartInfo['items'] as $item) {
$aFormData['x_line_item'][] = implode('<|>', $aCartInfo['items']).'<|>N',
}

Categories