Understanding variable assignment in a foreach loop [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a pretty basic question:
What is this statement actually doing (specifically the =>$p)?
foreach ($email->parts as $partno=>$p) {
I understand the the basics but the =>$p is not clear

In a foreach loop you can ask for both the key and value to be returned
$array = array('cat' => 'Tom', 'mouse' => 'Jerry');
foreach($array as $animal => $name) {
echo $name . ' is a ' . $animal . '<br>';
}
So the loop will output
Tom is a cat
Jerry is a mouse

This synthax is to assign the array key name or object property name to the variable $partno and it's value to $p.
This way you can do for instance $email->parts[$partno] = $p;.
It can be particularly useful if you have parallel arrays with different information bound by the key, so you need this information to obtain related data from the other array when iterating one of them.
For instance:
$person = array(
1 => 'Santa Claus',
2 => 'Homer Simpson',
3 => 'Papa Smurf'
);
$location = array(
1 => 'North Pole',
2 => 'Springfield',
3 => 'Smurf village'
);
foreach ($person as $id => $name)
echo "$name live in {$location[$id]}\n";

$partno is the key, $p is value
e.g. $email->parts = array("key" => "value");
Read this
http://www.php.net/manual/en/control-structures.foreach.php

Related

Convert one dimensional key-value array into two dimensional kay-value array every nth key with new key names [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an array that looks like this:
And I need to translate it into this:
Some things to know about the $startArray is that it is dynamic based on the amount of people submitted on a form. Each person always has just those three fields though (custom_12, custom_13, custom_14 aka fName, lName, email). So if there were 5 members, the 5th members fName would be the key custom_12-5 in the start array.
I've been looking around on stackoverflow for a question just like this and I was not able to find one. What would be the steps taken and possible array functions or anything else for creating the $endArray ?
There's actually a builtin function for this: https://www.php.net/manual/en/function.array-chunk.php
For example, array_chunk($startArray, 3) will give you the base for your new array, you'll just need to then iterate through it and rename the keys.
Alternatively, just iterate through the array yourself and add the values to a new array depending on the index of the current iteration.
Thanks to Charlie's advice, I came up with this.
$startArray = array(
'custom_12' => 'john',
'custom_13' => 'johny',
'custom_14' => 'john#johny.com',
'custom_12-2' => 'bob',
'custom_13-2' => 'bobby',
'custom_14-2' => 'bob#bobby.com',
'custom_12-3' => 'don',
'custom_13-3' => 'donny',
'custom_14-3' => 'don#donny.com'
);
$middleArray = array_chunk($startArray, 3);
$endArray = array_map(function($val) {
return array(
'fName' => $val[0],
'lName' => $val[1],
'email' => $val[2]
);
}, $middleArray);
echo "<pre>";
print_r($endArray);
echo "</pre>";
And the output is exactly what I wanted:

Way to apply HTML code to each element of php array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm building a gallery application and I've been having Issues finding out If there Is a way I can put HTML around each PHP array value In my case images,
I believe that If I echo It I'll get the values as text. I don't want to echo the values as text any options?
Thanks in advance.
If I understand correctly the following may be of some help, If you want to display the images in HTML you could use something like the following.
$images = array(
"1" => "image1.png",
"2" => "image2.jpeg",
"3" => "image3.gif"
);
foreach ($images as $key => $image) {
echo "<img src=\"{$image}\" alt=\"image {$key}\"/>";
}
and if you want to place the images inside HTML and back into your array you can use the following.
$images = array(
"1" => "image1.png",
"2" => "image2.jpeg",
"3" => "image3.gif"
);
foreach ($images as $key => $val) {
$images[$key] = "<img src=\"{$val}\" alt=\"image {$key}\"/>";
}
Not sure if this is just a "coders block", but it's very simple. grab the array, iterate it, wrap the output of each array element in a div and echo it back to the requesting page.
foreach($array as $item):
echo '<div>', $item ,'</div>';
endforeach;
Option 1
You seem to be looking for array_walk:
bool array_walk(array &$Input, callable $Fn [, mixed $extra = null ])
Applies the user-defined function Fn to
each element of the array Input, optionally
passing it the user-specified object $extra.
This is an example of wrapping every element of the array between two user-specified values.
<?php
$arry = array(
'pear',
'orange',
'banana',
);
array_walk($arry, function(&$item, $key, $data) {
$item = $data['before'].$item.$data['after'];
}, array(
'before' => 'this is a ',
'after' => ' squash.',
));
print_r($arry);
?>
Output:
Array
(
[0] => this is a pear squash.
[1] => this is a orange squash.
[2] => this is a banana squash.
)
Option 2
Another option could be that of using preg_replace_callback to perform a bulk replace on each element. This allows greater flexibility both in specifying what to replace, and how to replace it:
<?php
$arry = array(
'pear squash',
'squishy orange',
'squoshed banana',
);
// FIRST - wrap everything in double round brackets
$arry = preg_replace_callback('/^.*$/', function($matches){
return "(($matches[0]))";
}, $arry);
// SECOND - convert anything like "SQUASH" (but with whatever letter instead
// of the "A" - to "juice":
$arry = preg_replace_callback('/(.*)squ(.)sh(.*)/', function($matches){
// $matches[2] contains the whatever letter.
return $matches[1].'juice'.$matches[3];
}, $arry);
print_r($arry);
returns now
Array
(
[0] => ((pear juice))
[1] => ((juicey orange))
[2] => ((juiceed banana))
)

Sort PHP Numerically & Identify which is closest to date [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got an array for events on my site that looks like this:
array(
'title' => 'Name',
'link' => 'http://www.eventssite.com',
'image' => '_img/event_img.jpg',
'location' => 'Florida, US',
'year' => '2013',
'date' => 'Dec. 12-14',
'desc' => 'Description about the event.',
'dateid' => '1212013'
),
I'd like to sort the array before the foreach by the dateid so that they show in the proper Date order.
Additionally I'm trying to identify which one of the events is closest to the actual date, as I am using a carousel type system that needs to know which to display first.
I've researched usort and am not able to get it to go on my own, Thank you for any assistance on these!
Using this function: http://php.net/usort
An example would be something like:
<?php
//just an array of arrays with the date as one of the values of the array
$array = array(
array(
'date' => '05/02/1988',
'name' => 'Jacob'
),
array(
'date' => '12/12/1968',
'name' => 'Sherry'
),
array(
'date' => '05/15/1978',
'name' => 'Dave'
)
);
//usort is used for non conventional sorting.
//which could help in this case
//NOTICE - we are not setting a variable here!
//so dont call it like $array = usort(...) you will just be setting $array = true
usort($array,'sortFunction');
//display the results
var_dump($array);
//function called by usort
function sortFunction($a,$b){
//turn the dates into integers to compare them
//
$strA = strtotime($a['date']);
$strB = strtotime($b['date']);
//don't worry about sorting if they are equal
if($strA == $strB){
return 0;
}
else{
//if a is smaller than b, the move it up by one.
return $strA < $strB ? -1 : 1;
}
}
?>
(in case youre interested, line 40 is called a Ternary)
edited for clarity

Create multidimentional array from SQL table [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have a table 'GOAL':
ID TYPE KEY VALUE
-- ---- --- -----
1 RED BASE 3
2 BLUE NAME ALLOR
3 RED MAIN _TTR
4 GREEN LOCAL PIN,SEC,BALL,UNI
5 BLUE ALT 2DFFRST34#HH&FR#
6 GREEN DOMAIN SITE.ORG,NSPL.EDU,ROAR.IN
I want to create a multidimentional array in PHP which will produce this array:
$GOAL = array (
'RED' => array (
'BASE' => 3,
'MAIN' => '_TTR'
),
'BLUE' => array(
'NAME' => 'ALLOR',
'ALT' => '2DFFRST34#HH&FR#'
),
'GREEN' => array(
'LOCAL' => 'PIN,SEC,BALL,UNI',
'DOMAIN' => 'SITE.ORG,NSPL.EDU,ROAR.IN'
)
);
What should be the query?
Someting like this should work
<?php
$query = mysql_query('SELECT * FROM GOAL');
$goal = array();
while($row = mysql_fetch_object($query)) {
if(!isset($goal[$row->type])) {
$goal[$row->type] = array();
}
$goal[$row->type][$row->key] = $row->value;
}
?>

PHP Multiple Arrays [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I have the following example array:
Array
(
[0] => Array
(
[artist] => Artist43141
)
[1] => Array
(
[artist] => Artist2313
)
[2] => Array
(
[artist] => ArtistAdsa
)
[3] => Array
(
[artist] => ArtistAadas
)
)
How do I turn it into something like: "Artist43141, Artist2313, ArtistAdsa, ArtistAadas"
I'd like to know because as far as I tried with some similar questions already answered I wasn't able to find out how.
I would say something like this would work just fine:
$newArray = array_map(function($a) {return $a['artist'];},$oldArray);
No need for loops, or anything so complicated.
You want to create a space separated string containing only the values of the array.
To do so, try:
<?php
$array = Array
(
array(
'artist' => 'Artist43141'
),
array(
'artist' => 'Artist2313'
),
array(
'artist' => 'ArtistAdsa'
),
array(
'artist' => 'ArtistAadas'
),
);
$str = implode(' ', array_map(function($a){ return current($a); }, $array));
Check the PHP Manual for current() and array_map() to learn more about what the above example is doing.
Happy coding!
EDIT:
According to your comment:
I have one more issue, one of my artist values has a special character 'é', and now it doesn't print them. Where should I apply the htmlspecialchars() (if that's supposed to apply)?
…I want to add the following to this answer:
Modify the above code example like this to handle character encoding (assuming you're using UTF-8 encoding):
$str = implode(' ', array_map(function($a)
{
return htmlentities(current($a));
}, $array));
In case you're not using utf8 yet, start doing so by adding this to your php codes which echo to the browser:
header('Content-Type: text/html; charset=utf-8');
or the following in the header section of your html files:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8" />
...
So read up on PHP's htmlentities() and utf8 encoding.
Have fun.

Categories