display array data by city - php

I have an array with this structure:
array(4) {
[0]=> array(x) {
[0]=> string(x)"London"
[1]=> string(xx) "John"}
[1]=> array(x) {
[0]=> string(x)"London"
[1]=> string(xx) "Charles"}
[2]=> array(x) {
[0]=> string(x)"Paris"
[1]=> string(xx) "Alan"}
[3]=> array(x) {
[0]=> string(x)"Paris"
[1]=> string(x) "Wayne"}
}
How can I display the array data in this order:
London
John | Charles
Paris
Alan | Wayne
This can be done with an unique multidimensional array? or should i have another array to select distinct cities?
I am talking about something like a loop with:
foreach ($cities as $city) {
echo '<div class="city">'.$city.'</div>';
for() {
echo '<div class="persons">'.$persons.'</div>';
}
}
thanks

Group your cities in a new array, then spit it out
$newCities = array();
foreach ($cities as $city) {
$newCities[$city[0]][] = $city[1];
}
foreach($newCities as $city => $persons) {
echo '<div class="city">' . $city . '</div>';
// use join to glue the pieces together
echo '<div class="persons">' . join(' | ', $persons) . '</div>';
}

It might be convenient to create a new associative array as an intermediate step. This method doesn't care if the cities are originally grouped or not.
$cities = array();
foreach ($original_array as $entry) {
$cities[$entry[0]][] = $entry[1];
}
The new array will contain city names as keys, and an array of people's names as corresponding values for each city. Like:
array(2) {
["London"]=> array(2) {
[0]=> "John"
[1]=> "Charles" }
["Paris"]=> array(2) {
[0]=> "Alan"
[1]=> "Wayne" }
}
So now you can do
foreach ($cities as $city_name => $people) {
echo '<div class="city">'.$city_name.'</div>';
foreach ($people as $person) {
echo '<div class="person">'.$person.'</div>';
}
}

Try this
$array = array(
array('0' => array('0' => 'London', '1' => 'John')),
array('1' => array('0' => 'London', '1' => 'Charles')),
array('2' => array('0' => 'Paris', '1' => 'Alan')),
array('3' => array('0' => 'Paris', '1' => 'Wayne'))
);
$i = 0;
foreach ($array as $arr1) {
foreach ($arr1 as $arr2) {
$cities[$arr2[0]][$i] = array($arr2[0],$arr2[1]);
$i++;
}
}
foreach ($cities as $key => $city) {
echo '<h2 class="city">'.$key.'</h2>';
foreach($city as $persons) {
echo '<div class="persons">'.$persons[1].'</div>';
}
echo '<br/>';
}

I think it may help
foreach ($cities as $city) {
echo '<div class="city">'.$city.'</div>';
foreach ($cities as $city1) {
if ($city==$city1){
echo '<div class="persons">'.$persons.'</div>';
}
}
}

Since cities are always grouped as you specified, you only need one extra variable to do this properly. Assuming your input array is called $people:
$last_city = '';
foreach ($people as $person) {
if ($person[0] != $last_city) {
if ($last_city != '') echo '</div>'; // Close opened persons block
$last_city = $person[0];
echo '<div class="city">' . $last_city . '</div>';
echo '<div class="persons">';
}
else echo ' | ';
echo $person[1];
}
echo '</div>'; // This assumes there's at least one record in $people
No extra associative array required. Note that this may be more semantic markup:
<div class="city">
<span>London</span>
John | Charles
</div>
In that case the above code would be:
$last_city = '';
foreach ($people as $person) {
if ($person[0] != $last_city) {
if ($last_city != '') echo '</div>'; // Close opened city block
$last_city = $person[0];
echo '<div class="city">';
echo '<span>' . $last_city . '</span>';
}
else echo ' | ';
echo $person[1];
}
echo '</div>'; // This assumes there's at least one record in $people

Related

Create array from string - PHP

I have a string from which I need to get an associative array. I can freely modify the string to look like an array, but I still can't get an array out of it.
I tried explode, json, etc.
$string = $row->id . ',' . $row->title . ',';
// 1,Home,3,Services,6,Service 1,7,Service 2,2,Products
example
public function Menu($parent = null) {
$query = $this->menuManager->getPublicMenus()->where('parent', null)->order('sort_order');
if ($this->menuManager->getPublicMenus()->count() > 0) {
$menu = '';
foreach ($query as $row) {
$menu .= $row->id . ',' . $row->title . ',';
$menu .= $this->Menu($row->id);
}
return $menu;
}
}
I need output:
array
1 => "Home"
3 => "Services"
6 => "Service 1"
7 => "Service 2"
2 => "Products"
In case you HAVE TO use the string.
$input = '1,Home,3,Services,6,Service 1,7,Service 2,2,Products';
$keysAndValues = explode(',', $input);
$result = [];
$count = count($keysAndValues);
for ($i = 0; $i < $count; $i+=2) {
$key = $keysAndValues[$i];
$value = $keysAndValues[$i+1];
$result[$key] = $value;
}
Working example.
output
array(5) {
[1]=>
string(4) "Home"
[3]=>
string(8) "Services"
[6]=>
string(9) "Service 1"
[7]=>
string(9) "Service 2"
[2]=>
string(8) "Products"
}
I see you added an example. To get the array, its much cleaner to do this in your Menu method:
$menu = [];
foreach ($query as $row) {
$menu[$row->id] = [
'title' => $row->title,
'children' => $this->Menu($row->id)
];
}
return $menu;

PHP - echo an array within a session array

So I'm trying to use a foreach loop to echo out all the values of an array in my $_SESSION array as follows.
<?php
foreach($_SESSION['movie'] as $key => $value){
echo "Movie: " . $key;
}
foreach($_SESSION['session'] as $key => $value){
echo "Session: " . $key;
}
?>
I'm pretty new to PHP so don't have much idea if I'm even on the right track.
This is the var_dump of the $_SESSION array.
array(1) {
["cart"]=> array(2) {
["ACWED-09"]=> array(3) {
["movie"]=> string(2) "AC"
["session"]=> string(6) "WED-09"
["seats"]=> array(1) { ["SF"]=> int(7) }
}
["ACFRI-09"]=> array(3) {
["movie"]=> string(2) "AC"
["session"]=> string(6) "FRI-09"
["seats"]=> array(1) { ["SF"]=> int(2) }
}
}
}
The movie is nested in the $_SESSION['cart'] array. You need to do:
foreach ($_SESSION['cart'] as $key => $item) {
echo "Key: $key<br>";
if (isset($item['movie']) {
echo "Movie: {$item['movie']}<br>";
}
if (isset($item['session']) {
echo "Session: {$item['session']}<br>";
}
}
You should try this..
foreach($_SESSION['movie'] as $key => $value) {
echo 'Movie ' . $value . '<br/>';
}
echo '<hr/>';
foreach($_SESSION['session'] as $key => $value) {
echo 'Session' . $value . '<br/>';
}
An array pairs values to keys, as stated here. Keys are the indexes in the array.
foreach($_SESSION['movie'] as $key => $value){
echo "At the index " . $key . ", the movie is " . $value;
}
So you should go with echo "Movie: " . $value; if you want to write the value. The key isn't relevant here.
Note that you don't have to use the "$key => $value" pairing if you don't care about the indexes within your loop. This works too :
foreach($_SESSION['movie'] as $value){
echo "Movie: " . $value;
}
You don't have access to the value's index in that case.
foreach($_SESSION['movie'] as $key => $value){
echo "Movie: " .$key."=". $value;
}
foreach($_SESSION['session'] as $key => $value){
echo "Session: " .$key."=". $value;
}
Here is an example for associative array what is key and what is value
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
foreach ($_SESSION['cart'] as $key => $item) {
echo "Key: $key<br>";
echo "Movie: {$item['movie']}<br>";
echo "Session: {$item['session']}<br>";
}

How to loop to this array

i have this array as output.
array(2) { ["Datum"]=> string(10) "2017-05-29" ["ID"]=> array(2) { [2]=> string(19) "75528705-1431953348" [3]=> string(21) "1081357825-1445504448" } }
how can i loop through this array in php ?
this is the code to read the array
<?php
var_dump($_POST);
$val = $_POST;
?>
I have already try this
<?php
foreach($_POST->ID as $val) {
print "waarde = " . $val . " <BR>";
}
?>
This is a declaration of your provided $_POST array:
$_POST=array(
"Datum" => "2017-05-29",
"ID" => array(
2 => "75528705-1431953348",
3 => "1081357825-1445504448"
)
);
You can directly access any of its elements by referencing its keys:
echo $_POST["Datum"]; // prints 2017-05-29
print_r($_POST["ID"]); // prints Array([2] => 75528705-1431953348 [3] => 1081357825-1445504448 )
echo $_POST["ID"][2]; // prints 75528705-1431953348
echo $_POST["ID"][3]; // prints 1081357825-1445504448
You are not dealing with an object, so the -> will not work.
Using a foreach loop on the $_POST["ID"] subarray will let you access all of the elements in the subarray.
Code:
foreach($_POST["ID"] as $val){
echo "waarde = $val<br>";
}
Output:
waarde = 75528705-1431953348
waarde = 1081357825-1445504448
<?php
foreach($_POST['ID'] as $index => $str) {
echo "waarde = " . $str . "<br/>";
}
?>

How to loop and get serialized values from database with php

I'm developing a pizza's restaurant ecommerce and now I'm trying to get the size (Familiar) and the ingredients (Pernil dol�, Bac�, Emmental) of a pizza that was ordered previously. The data I want to get (the italic values in this paragraph) becomes serialized from database:
a:4:{s:10:"attributes";a:2:{s:6:"Tamany";a:1:{i:3;s:8:"Familiar";}s:11:"Ingredients";a:3:{i:318;s:12:"Pernil dol�";i:270;s:5:"Bac�";i:294;s:8:"Emmental";}}s:9:"shippable";s:1:"0";s:4:"type";s:5:"pizza";s:6:"module";s:10:"uc_product";}array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
I discovered 'unserialized' php method and I tried this:
$attr = $row['data']; // data from database
$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $attr); // I did this because I get some errors...
After I did that, I got this multidimensional array (a bit more human readable):
array(4) { ["attributes"]=> array(2) { ["Tamany"]=> array(1) { [3]=> string(8) "Familiar" } ["Ingredients"]=> array(3) { [318]=> string(11) "Pernil dol�" [270]=> string(4) "Bac�" [294]=> string(8) "Emmental" } } ["shippable"]=> string(1) "0" ["type"]=> string(5) "pizza" ["module"]=> string(10) "uc_product" }
Next step was try to loop the resulting data with a foreach loop, like the following:
foreach($data['attributes'] as $item)
{
print '<ul>';
foreach($item as $value)
{
print_r('<li>' . $value . '</li>');
}
print '</ul>';
}
I'm a php beginner PHP developer and I can't figure out how can I loop this array in order to get the values I need. I'm getting this error:
Warning: Invalid argument supplied for foreach() in /home/my_host/public_html/dev.mysite.com/inc/file.php on line 79
Can anybody tell me how I have to loop this array to get the data?
Any help will be very, very appreciated.
Best regards,
I created this example for you. First I declared an array which believe mimics the array you have to parse. Then I looped through and outputed the contents of the array.
<?php
$array = array(
0 => array(
'0' => 'John Doe',
'1' => 'john#example.com'
),
1 => array(
'0' => 'Jane Doe',
'1' => 'jane#example.com'
),
);
foreach ($array as $key => $value) {
$thisArray = $array[$key];
print_r('<ul>');
foreach ($thisArray as $key2 => $value){
print_r('<li>'.$thisArray[$key2].'</li>');
}
print_r('</ul>');
}
?>
Finally, and based on the answer of #Gregory Hart, I reached my goal. This is the final code that makes it possible in my particular case:
$data = $row['data'];
$attrib = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data);
$attr = unserialize($attrib);
foreach ($attr as $key => $value)
{
print_r('<ul>');
$thisArray = $attr[$key];
foreach ($thisArray as $key2 => $value2)
{
print_r('<li>' . $key2 . ': ');
$thisArray2 = $attr[$key][$key2];
foreach ($thisArray2 as $key3 => $value3)
{
if ($key2 == 'Tamany')
print_r('<span class="label label-warning">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Ingredients')
print_r('<span class="label label-success">' . utf8_encode($thisArray2[$key3]) . '</span> ');
if ($key2 == 'Salsa')
print_r('<span class="label label-primary">' . utf8_encode($thisArray2[$key3]) . '</span> ');
}
print '</li>';
}
print_r('</ul>');
}
Thanks for you help!
Try this logic:
$data_unserialize = unserialize($row->data);
foreach ($data_unserialize as $data_key => $data_value) {
if($data_key =='size')
{
$thisArray = $data_unserialize[$data_key ];
foreach ($thisArray as $key2 => $value2){
if($key2=='attributes')
{
switch ($value2)
{
case "Pernil dol�":
echo'Pernil dol �';
break;
case "Emmental":
echo'Emmental';
break;
default:
echo 'Nothing';
}
}
}
}
}
NB:- And remove the break; from switch statement to display all ingrediants.

How to access array elements

I am getting this as var_dump:
array(1) {
[0]=>
array(4) {
["num"]=>
string(1) "1"
["yyyy"]=>
string(4) "2013"
["mm"]=>
string(2) "12"
["dd"]=>
string(2) "11"
}
}
How to access the array elements?
Let's assume your array is $arr, you can do
echo $arr[0]['num'];
echo $arr[0]['yyyy'];
echo $arr[0]['mm'];
echo $arr[0]['dd'];
As you are fetching from a database, you will receive an array for each result row, and within each array will be another array of columns. you can use a foreach() loop to iterate over the data, as follows:
foreach($arr as $row) {
echo $row['num'] . ':' . $row['yyyy'] . '-' . $row['mm'] . '-' . $row['dd'] . "\n";
}
try this
foreach($array as $value) {
foreach($value as $k=>$v) {
echo $k . " : " . $v .'<br/>';
}
echo '<hr>';
}
Please have a look at the official PHP Doc article about arrays.
In your case:
$yourArrayVariable[0]['yyyy']
Will let you access the element with value 2013.
Or if you have an undefined number of array entries you can iterate over it with either foreach or for.
foreach($yourArrayVariable as $key => $value) {
echo $key , ': ' , $value , '<br>';
}
or if you have only numeric indeces without a gap:
$arrCount = count($yourArrayVariable);
for($i = 0; $i < $arrCount; ++$i) {
echo $i , ': ' , $arrCount[0] , '<br>';
}
store array in a variable like
$arr =array(1) {
[0]=>
array(4) {
["num"]=>
string(1) "1"
["yyyy"]=>
string(4) "2013"
["mm"]=>
string(2) "12"
["dd"]=>
string(2) "11"
}
}
for access array elements you have to use following code
echo $arr[0]['num'];
echo $arr[0]['yyyy'];
echo $arr[0]['mm'];
echo $arr[0]['dd'];o $arr[0]['num']
$arr =Array(
0=>array(
"num"=>"1",
"yyyy"=>"2013",
"mm"=>"12",
"dd"=>"11",
)
);
foreach ($arr as $value) {
echo "num: ".$value["num"];
echo "yyyy: ".$value["yyyy"];
echo "mm: ".$value["mm"];
echo "dd: ".$value["dd"];
}
You can get the value using echo $array[0]['num']; gives output as 1
$array ='your array data here';
foreach($array as $key=>$value) {
echo "num: ". $value['num'] . "/yyyy: ". $value['yyyy']. " /mm: ". $value['mm'] . " /dd: ". $value['dd'] . "<br>";
}

Categories