I Want To Get ID From Link i have set all links in array and explode forward slash / and then loop it but i'm getting only one id main link in array
"/4tzCuIpHHhc/long-title-here", i need this id 4tzCuIpHHhc
i'm trying this
<?php
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s = $explode_c[1];
}
echo $s;
?>
Make $s as array
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1];
}
print_r($s);
You can do like this, replace your with below:
$links = array(
"/WSNINQJZj1s/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-run-nam-joo-hyuk-errand-20161130",
"/Nmy5FWgX0S0/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuk-reject-a-proposal-20161130",
"/u3gumA7-38A/weightlifting-fairy-kim-bok-ju-ep05-did-you-fall-in-love-with-my-brother-20161130",
"/Zsa_saeRT1E/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-offered-joo-hyuk-a-deal-20161130",
"/9q0uUfSr0lE/weightlifting-fairy-kim-bok-ju-ep05-nam-joo-hyuks-angry-at-lee-sung-kyung-20161130",
"/UH6YqMDdMDE/weightlifting-fairy-kim-bok-ju-ep05-sung-kyung-and-lee-jae-yoons-drive-date-20161130",
"/5pC2NJtCg_I/weightlifting-fairy-kim-bok-ju-ep03-did-you-fight-because-of-me-20161123",
"/UbxbVugdIdo/weightlifting-fairy-kim-bok-ju-ep01-lee-sung-kyung-fell-into-the-pool-20161116",
"/f29SpSqcOQc/weightlifting-fairy-kim-bok-ju-ep03-lee-sung-kyung-got-into-trouble-20161123",
"/ydWm_Pnp1BQ/weightlifting-fairy-kim-bok-ju-ep04-lee-sung-kyung-vs-nam-joo-hyuk-20161124",
"/uiLlQSexJr4/weightlifting-fairy-kim-bok-ju-ep01-an-underwear-thiefs-identity-20161116",
"/4tzCuIpHHhc/weightlifting-fairy-kim-bok-ju-ep01-weightlifter-vs-rhythmic-gymnast-20161116",
"/QzRi9_4-ItQ/weightlifting-fairy-kim-bok-ju-ep05-lee-sung-kyung-enter-a-contest-instead20161130",
);
foreach ($links as $result) {
$explode_c = explode('/',$result);
$s[] = $explode_c[1]; // made array of exploded string
}
echo "<pre>";
print_r($s);
$result = array_search('4tzCuIpHHhc', $s); // search for the string if you need key from $s
echo $id = $s[11];// $result = 11
Related
This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
I use dom parser to grab text from two html documents with the same li class and I retrieved a double value.
<?php
include_once('simple_html_dom.php');
$links = array (
"Model_one" => "car.html",
"Model_two" => "car/edition.html"
);
foreach ($links as $key=>$link) {
$html = file_get_html($link);
$ret[] = $html->find('ul li[class=dotCar]',0)->plaintext;
$pattern = '/.\d+(?:\.\d{2})?((?<=[0-9])(?= usd))/';
preg_match_all($pattern, $ret[0], $result);
$price = array();
foreach($result[0] as $k=>$v) {
$price[] = $v;
echo $price[0];
}
}
// $price[0]= 10.55 11
?>
How can I associate the model_key from $links array to value $price to obtain the result:
model_one 10.55
model_two 11.00
In this way I can retrieve the single value to insert in a MySQL table.
Perhaps something like this:
foreach($result as $k=>$v) {
//$v is the price (10.55 etc.)
foreach($links as $kk=>$vv) {
//$vv is the link (model_one etc.)
$priceAndLinks[$vv] = $v;
}
}
This might give you an idea of the logic needed.
I have an array returned from sql and I need to get them into separate strings to use on the page. It is out of a single row in the database and lists all the folders a user has.
example in database john has a red folder, green folder, blue folder.
I run the query and use fetchAll to return john's folders. I have it in an array. I can echo the array and it outputs redfoldergreenfolderbluefolder
How can I take the array and split it into separate strings?
PHP code
$query = "SELECT album_name FROM albums WHERE username = :username";
$query_params = array(
':username' => $email
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
echo 'Database Error, please try again.';
}
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
The below needs correction :
foreach ($rows as $row) {
$post = array();
$post["album_name"] = $row["album_name"];
echo $post["album_name"]; // This just lists all albums together no spaces or commas
}
$text = implode(",", $post);
echo $text; // This just outputs the last item (bluefolder)
Change the above to :
$post = array();
foreach( $rows as $row )
{
// $post = array(); // This line should not be here . It should be outside and above foreach
// The below echo is for test purpose . Comment it if you don't need it
echo $row["album_name"] ,' ';
// $post["album_name"] = $row["album_name"]; // This keeps assigning $row["album_name"] to same index "album_name" of $post . Eventually you will have only one value in $post
$post[] = $row["album_name"];
}
// $text = implode(",", $post); // With coma's as separator
$text = implode(" ", $post); // With blank's as separator
echo 'John has ' , $text;
try print_r($post); on your last line.
please use print_r($text) in side the for each and then you will get all the arry with commos
and remove $post = arry from there and put above of foreach.
i am trying to help you,may this help
thanks
anand
Try this:
$post = array();
foreach ($rows as $row) {
array_push($post, 'album_name', $row["album_name"]);
}
$text = implode(",", $post);
echo $text;
No assoc ver:
$post = array();
foreach ($rows as $row) {
$post[] = $row["album_name"];
}
$text = implode(",", $post);
echo $text;
The reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
1: http://php.net/manual/en/function.imThe reason why it only show the last folder is because you do "$post = array()" at the beginning of your loop. It reset the array everytime... just take it out of the loop and put it above the foreach.
EDIT:
Try it this way :
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$post = array();
foreach ($rows as $key => $folder) {
array_push($post, $folder)
}
$text = implode(",", $post);
The following code returns an associated array with a url,title and snippet from a search engine and it works fine
$js = json_decode($data);
$blekkoArray = array();
$find = array ('http://','https://','www.');
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$i++;
}
print_r ($blekkoArray);
I'm trying to add another value to the array so that I can score each element, eg. I want the first result to have a score of 100, the second 99, the third 98 and so on, the following code spits out the same as the above. Therefore I can't seem to add 'score' the the array, any thoughts.
Reagrds
$js = json_decode($data);
$blekkoArray = array();
$find = array ('http://','https://','www.');
foreach ($js->RESULT as $item)
{
$score = 100;
$blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'];
$i++;
$score--;
}
print_r ($blekkoArray);
You have done 2 mistakes.
1) you have initialized $score inside foreach loop, it should be outside otherwise you will get $score = 100 always.
2) You are not assigning the $score in array,
$score = 100; // move the initialization of $score outside of loop
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = str_replace ($find, '', ($item->{'url'}) );
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'] = $score; // assign the $score value here
$i++;
$score--;
}
OR suggested by u_mulder
$blekkoArray[$i]['score'] = $score--;
Bring the $score = 100; outside of the foreach array. You're resetting it to 100 each loop.
And use
$blekkoArray[$i]['score'] = $score--;
or the same on two lines:
$blekkoArray[$i]['score'] = $score;
$score--;
And next to that, can't you use the key in the foreach? Like this? This is just a guess, as I don't know what $i is. It's not defined or initialised in your code, so...
And a little bonus modification: if you're not using variables as fieldnames, the $var->{'fieldname'} notation can be simplified to $var->fieldname.
All together, this is giving the following code:
$score = 100;
foreach ($js->RESULT as $i => $item)
{
$blekkoArray[$i]['url'] = str_replace ($find, '', $item->url);
$blekkoArray[$i]['title'] = $item->url_title;
$blekkoArray[$i]['snippet'] = $item->snippet;
$blekkoArray[$i]['score'] = $score--;
}
THE ANSWER THAT WORKED FOR ME BASED ON AN ANSWER GIVEN
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
$array = array_merge($array, $push);
}
So I'm trying to display tags from my data base and make links out of them like this:
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
$array = array();
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_push($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
<? }
?>
However all I get back is
Array
Where I should be having at least three lines as was previously produced by
<?
$tags = mysql_query( 'SELECT tags FROM `Table`');
while($post = mysql_fetch_array($tags)) {
$array = explode(',', $post['tags']);
foreach ($array as $value) {?>
<? echo $value?>
<? }
}
?>
The code being called looks like this:
tag1, tag2, tag3
Tried
while($post = mysql_fetch_array($tags)) {
$push = explode(',', $post['tags']);
array_merge($array, $push);
}
foreach ($array as $value) {?>
<? echo $value?>
now foreach doesn't return a value
Use array_merge(), because array_push() will push the output of explode(), which is an array, as a whole to the array in the first argument, creating a jagged array.
As for your edit, this works:
$array = array_merge($array, $push);
foreach ($array as $value)
{
echo '' . $value . '';
}
Please note that array_merge() (contrary to array_push(), gotta love the consistency) does not alter the array passed as its first argument, so you'll have to store the return value which I do on the first line ($array = ...).
While outputting to HTML, you also might want to put a $value = htmlentities(trim($value)); in the foreach loop.