How to add values to string in foreach? - php

I have an array with lots of information. I want to extract some of the information:
*to a string
*To a new array
I tried doing this for a string:
$output;
foreach ($response->data as $post){
$output = $output . $post->link;
}
echo $output;
but the $output inside the foreach is undefined.
Is this a good solution? In that case how do I declare a variable with the right scope?

Your error appears because you're not initialising the $output variable at the beginning.
Try $output = ""; instead.
But on the other hand, a more elegant solution would be to use PHP's built-in implode() method.
Manual:
http://php.net/manual/en/function.implode.php
You could do something like this:
$output = implode(" ", $response->data);
echo $output;
UPDATE
If you want to 'implode' associative arrays, linepogl's answer to this question provides a nice example: Imploding an associative array in PHP
UPDATE 2
Here's an updated code that actually deals with the ->link part of your question:
$response_array = array();
foreach ($response->data as $post) {
$response_array[] = $post->link;
}
$output = implode(" ", $response_array);
echo $output;

You must define the variable before using it in foreach. Like:
$output="";
instead of
$output;

try this code
$output = '';
foreach ($response->data as $post){
$output = $output . $post->link;
}
echo $output;
.

Try
$output = '';
foreach ($response->data as $post){
$output .= $post->link;
}
echo $output;

Try like
$output = '';
foreach ($response->data as $post){
$output .= $post->link;
}
echo $output;
First you need to initialize the $output value as null thenonly in foreach loop concat the result to the $output.

$output = '';
foreach ($response->data as $post){
$output .= $post->link;
}
echo $output;
or you can use join
$output = join('',$response->data);

$output = array();
foreach ($response->data as $post){
$output[] = $post->link;
}
foreach( $output as $key => $value ){
echo $value;
}
To your code you might do:
$output = NULL;
foreach ($response->data as $post){
$output .= $post->link;
}
echo $output;

Related

Get certain strings only (PHP)

Text:
TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class
What I have so far: (Inside $display->getExtraHTML() is the text). Could someone guide me towards what I need to do to adapt my code to get the results I want.
<?php
$additionalHTML = explode("\n", $display->getExtraHTML());
$html = "";
$html .= "<ul>";
foreach($additionalHTML as $key => $item){
$html .= "<li>$item</li>";
}
$html .= "</ul>";
echo $html;
?>
I know I can use something like this to get string between, but how do I use it to get all the values i need?
$string = strstr($display->getExtraHTML(), "HT-"); // gets all text from HT
$string = strstr($string, "CLASS-", true); // gets all text before CLASS
Can I use both explode and strstr to get to where I want?
Expect HTML markup:
Expected Result: (Get the values from HT- and CLASS-)
<ul>
<li>Child1 Class1</li>
<li>Child2 Class2</li>
<li>Child3 Class3</li>
<li>Child4 Class4</li>
</ul>
Complete solution with preg_match_all function:
$txt = '
TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class';
preg_match_all('/^HT-(\S+)\s+CLASS-(\S+)/m', $txt, $m);
$html = "<ul>";
if (isset($m[1]) && isset($m[2])){
foreach(array_map(null, $m[1], $m[2]) as $pair){
$html .= "<li>". implode(' ', $pair) ."</li>";
}
}
$html .= "</ul>";
echo $html;
The output (push Run code snippet):
<ul><li>Child1 Class1</li><li>Child2 Class2</li><li>Child3 Class3</li><li>Child4 Class4</li></ul>
Here's the solution
<?php
$str = "TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class";
$additionalHTML = explode("\n", $str);
$html = "";
$html .= "<ul>";
foreach($additionalHTML as $key => $item){
if(substr($item,0,3) == "HT-") {
$i = explode(" ",$item);
$a = substr($i[0],3);
$b = substr($i[1],6);
$html .= "<li>$a"." ". "$b</li>";
}
}
$html .= "</ul>";
echo $html;
Result
Child1 Class1
Child2 Class2
Child3 Class3
Child4 Class4
You may use regex, to find the matching lines and extract required data:
if(preg_match("/HT-([A-Za-z0-9]+) CLASS-([A-Za-z0-9]+)/", $item, $output))
{
$html .= "<li>".implode(" ",array_slice($output,1))."</li>";
}

foreach loop - repeat foreach or store/echo result for second loop

This is regarding filtering the native gallery output for WordPress from answer: here
// Now you loop through each attachment
foreach ($attachments as $id => $attachment) {
// Fetch all data related to attachment
$img = wp_prepare_attachment_for_js($id);
// If you want a different size change 'large' to eg. 'medium'
$url = $img['sizes']['large']['url'];
$height = $img['sizes']['large']['height'];
$width = $img['sizes']['large']['width'];
$alt = $img['alt'];
// Store the caption
$caption = $img['caption'];
$output .= "<li>\n";
$output .= "<img src=\"{$url}\" width=\"{$width}\" height=\"{$height}\" alt=\"{$alt}\" />\n";
// Output the caption if it exists
if ($caption) {
$output .= "<div class=\"orbit-caption\">{$caption}</div>\n";
}
$output .= "</li>\n";
}
$output .= "</ul>\n";
$output .= "</div>\n";
return $output;
}
Is there a more efficient way of repeating the foreach loop output if the results are required again, rather than just repeating the foreach loop?
(Could use a different variable in foreach loop, but then not sure if it seems logical to disrupt concatenated output.)
Would appreciate logic or approach for insight.
You don't have to return $output inside the foreach like in a function. You can use the variable outside the loop on the same accesslevel.

Output text string in array

How do I print the following string in an array in PHP, only selecting the texts in lowercase:
{"fieldValue":[{"portfoliocategory":"Printing","portfoliocategoryid":"printing"},{"portfoliocategory":"Digitization","portfoliocategoryid":"digitization"},{"portfoliocategory":"Android App","portfoliocategoryid":"androidapp"},{"portfoliocategory":"Photography","portfoliocategoryid":"photography"},{"portfoliocategory":"Artwork","portfoliocategoryid":"artwork"}],"fieldSettings":{"autoincrement":1}}
Output should be:
<ul>
<li>printing</li>
<li>digitization</li>
<li>androidapp</li>
<li>photography</li>
<li>artwork</li>
</ul>
Thanks.
As I understand your question.
$input = '{"fieldValue":[{"portfoliocategory":"Printing","portfoliocategoryid":"printing"},{"portfoliocategory":"Digitization","portfoliocategoryid":"digitization"},{"portfoliocategory":"Android App","portfoliocategoryid":"androidapp"},{"portfoliocategory":"Photography","portfoliocategoryid":"photography"},{"portfoliocategory":"Artwork","portfoliocategoryid":"artwork"}],"fieldSettings":{"autoincrement":1}}';
$output = '<ul>'; // Store the output
$values = json_decode($input); // This will convert to an object
foreach ($values->fieldValue as $val) {
$output .= '<li>'.$val->portfoliocategoryid.'</li>';
}
$output .= '</ul>';
$output will give you the expected results.

Group PHP arrays by key value

Basically I'm trying to group my arrays like this:
Shopping
Amazon
Social
Amoeblo
American express
By using below PHP code:
<?php
echo '<ul id="list"><h2 class="searchresults"></h2>';
foreach($records as $catval) {
$sitechar = $catval->site_category;
echo '<h3 id="disappear">'. strtoupper($sitechar) .'</h3>';
echo '<li class="siteli"><a href="#" class="add">';
echo '<p id="text-site">'.$catval->site_name. '</p></a>';
echo '</li>';
}
echo '</ul>';
?>
But I'm getting values only like below.
Shopping
Amazon
Social
Amoeblo
Social
American express
I'm not getting the exact PHP sorting to use for this.
I would create a new array with categories as keys for arrays with the sites.
<?php
$arr = array();
// First create multidimensional array with categories as keys for site arrays
foreach($records as $catval) {
$sitechar = $catval->site_category;
if (!array_key_exists($sitechar, $arr)) {
// Set new array for a category if it does not exist
$arr[$sitechar] = array();
}
// Add site to category
$arr[$sitechar][] = array(
"name"=>$catval->site_name,
"image"=>$catval->site_img
);
}
// Then iterate the new array of categories
echo ("<ul>");
foreach($arr as $category => $sites) {
echo("<h3>" . $site_category "</h3>");
// Iterate array of sites
foreach($sites as $site) {
echo("<li>" . $site["name"] . "-" , $site["image"] . "</li>");
}
}
echo("</ul>");
?>
You can do it using a foreach and ksort
Let $your_array be the array you mentioned above
$res_array = array();
foreach($your_array as $val){
$res_array[$val->site_category][] = $val->site_name;
}
ksort($res_array);
print_r($res_array);
OR search for multisort in php which will solve your problem :)
$tmp = null;
echo '<ul id="list"><h2 class="searchresults"></h2>';
foreach($records as $catval) {
$myHtml = makeHtml($catval,$tmp);
echo $myHtml;
$tmp = $catval->site_category;
}
echo '</ul>';
function makeHtml($catval,$tmp){
if($tmp != $catval->site_category){ $html .= '<h3 id="disappear">'. strtoupper($catval->site_category) .'</h3>';}
$html .='<li class="siteli"><p id="text-site">'.$catval->site_name. '</p></li>';
return $html;
}

PHP - Split an array into chunks.

I have a variable on my page called, $recipe['ingredients'];
inside the var you have as follows,
100ml milk, 350ml double cream, 150ml water
and so on. Now I'm trying to split it up so it looks as follows
<ul>
<li>100ml milk</li>
<li>350ml double cream</li>
<li>150ml water</li>
</ul>
So far I have the following code,
$ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
$ingredients = array($ingredientsParts);
while (! $ingredients) {
echo" <li>$ingredients</li>";
}
But for some reason it doesn't work and I do not have the experience with explode to fix it.
$ingredientsParts = explode(',', $row_rs_recipes['ingredients']);
$li = '<ul>';
foreach($ingredientsParts as $key=>$value){
$li.=" <li>$value</li>";
}
$li.= '</ul>';
echo $li;
this should be enough:
$ingredientsParts = explode(', ', $row_rs_recipes['ingredients']);
foreach ($ingredientsParts as $ingredient)
{
echo "<li>$ingredient</li>";
}
or you can explode it by ',' and use echo '<li>' . trim($ingredient) . '</li>'; to remove whitespace from beginning/end of that string
When you explode() a string it is automatically converted into an array. You do not need to convert it to an array type as you did on the second line.
You want to use a foreach() loop to iterate through an array, not a while loop.
$ingredientsAry = explode(',', $row_rs_recipes['ingredients']);
foreach($ingredientsAry as $ingredient){
echo "<li>$ingredient</li>";
}
In fact you can just do a foreach() loop on the explode() value
foreach(explode(',', $row_rs_recipes['ingredients']) as $ingredient){
echo "<li>$ingredient</li>";
}
The explode method already return an array, so you don't have to transform your variable $ingredientsParts into an array.
Just do:
$ingredientsParts = explode(', ', $row_rs_recipes['ingredients']);
foreach ($ingredientsParts as $ingredient)
{
echo "<li>$ingredient</li>";
}
if (!empty($recipe['ingredients'])) {
echo '<ul><li>' . implode('</li><li>', explode(', ', $row_rs_recipes['ingredients'])) . '</li></ul>';
}
You can do this:
$ingredients = explode(',', $row_rs_recipes['ingredients']);
$list = '<ul>';
foreach ($ingredients as $ingredient)
{
$list .= '<li>' . $ingredient . '</li>';
}
$list .= '</ul>';
echo $list;

Categories