So, I am still learning PHP, and I wanted to customize the arrays a bit in matter of structure, so they are not static. But I've came to a problem. I've managed to write out each array that has an array inside of it, but now I struggle in finding a way of writing out the ones that do not have an array inside of them, and not to get 0-s and 1-s instead of the actual name of the array elements.
I basically need some advice on how to make this work properly, I wouldn't mind if you could tell me a more efficient way of writing everything out and solving the problem at the same time.
<?php
$food = array(
'Healthy'=>array( 'Salad'=> array('Fruit Salad','Tropical Salad'),
'Vegetables'=>array('Carrot','Cucumber'),
'Pasta'),
'Unhealthy'=>array('Pizza','Ice Cream')
);
foreach ($food as $type=>$food_types) {
echo '<b>'.$type.'</b>'.'<br>';
if (is_array($food_types)) {
foreach($food_types as $type_names=>$fruits) {
if (isset($type_names) && !empty($type_names) && is_array($fruits)) {
echo $type_names.'<br>';
foreach ($fruits as $name_of_fruits) {
echo '<i>'.$name_of_fruits.'</i>'.'<br>';
}
}
}
} else {
echo $food_types;
}
}
?>
**UPDATE***
Thanks to celeriko's comment I found the problem, being newbie to PHP I didn't really knew that the type of "Healthy Food" that was not an array was actually the first index of the big "Healthy Food" array, as the other two were array and didn't count as actual indexes.
Here is the fixed code, thank you cerleriko once again!
<?php
$food = array(
'Healthy'=>array( 'Salad'=> array('Fruit Salad','Tropical Salad'),
'Vegetables'=>array('Carrot','Cucumber'),
'Pasta'),
'Unhealthy'=>array('Pizza','Ice Cream')
);
foreach ($food as $type=>$food_types) {
echo '<b>'.$type.'</b>'.'<br>';
if (is_array($food_types)) {
foreach($food_types as $type_names=>$fruits) {
if (isset($type_names) && !empty($type_names) && is_array($fruits)) {
echo $type_names.'<br>';
foreach ($fruits as $name_of_fruits) {
echo '<i>'.$name_of_fruits.'</i>'.'<br>';
}
} else {
echo $fruits.'<br>'; /* Here I had to enter this line and everything works fine! */
}
}
} else {
echo $food_types;
}
}
?>
Glad you got it fixed, but as for the question "More dynamic way of outputting Multi-Dimensional Arrays", here is a recursive one. It sets a level-X class to the div that you can style:
function print_it($array) {
static $level = 1;
foreach($array as $k => $v) {
if(!is_numeric($k)) {
echo '<div class="level-'.$level.'">'.$k.'</div>'.PHP_EOL;
}
if(is_array($v)) {
$level++;
print_it($v);
$level--;
} else {
echo '<div class="level-'.$level.'">'.$v.'</div>'.PHP_EOL;
}
}
}
print_it($food);
Related
I have one array
$array = array(0=>array('id'=>1 ,'va'=>2),1=>array('id'=>3,'va'=>4));
With the help of two foreach() loop i can use it.
foreach($array as $temp)
{
foreach($temp as $key=>$val)
{
echo $key.'=>'.$val;
}
}
As array has more than 5 lacs record. this solution is not feasible for me.
Keys are dynamic so i can not put keys as static inside first for each loop.
I tried following code but till now did not get any solution.
function myfunction($value,$key)
{
foreach($value as $k=>$a)
{
echo $k.'=>'.$a;
}
}
$array = array(0=>array('id'=>1,'va'=>2),1=>array('id'=>2,'va'=>2));
array_walk($array,"myfunction");
And this one also
$keys = Array_keys($array['0']);
for($i=0;$<=count($array);$i++)
{
for($j=0;$j<count($keys);$j++)
{
echo $keys[$j].'=>'.$array[$i][$keys];
}
}
I want to make this code as optmize as possible.
I have managed to decode some JSON in PHP successfully (not as painful as I thought), but it's been such a long time since I've done any real PHP, my brain has drawn a blank on the following.
The decoded json looks like this
[Array]
item {
[0]
{
[live]=>
[name]=>Paul
[value]=>10
}
[1]
{
[live]=>1
[name]=>Fred
[value]=>32
}
and so on
The problem I'm having is this - I'm trying to iterate through the structure to test first if live==1 and then if it's the first live name, to output it as a selected value to a HTML drop down.
I'm currently trying like this
$t = 0;
$count = 0;
foreach($decode['items'] as $option=>$value)
{
print_r("option = $option\n");
if ($option=>isLive == 1)
{
print_r("isLive is true for $option[$count]['names']\n");
if ($t == 0)
{
echo "<option value=$option[name] selected>$value[name]</option>";
$t = 1;
}
else
echo "<option value=$option[name]>$value[name]</option>";
}
else
{
print_r("isLive is false for $option[$count]=>name\n");
}
$count++;
}
the problem is that I don't seem to be able to get the if statement correct for this to work. This is probably a seriously simple problem and will no doubt make me face palm, but I could do with a pointer in the right direction here!
If the json is like you showed us you could not iterate over anything with your foreach because your array does not contain a key named items.
Using the provided structure this should do the trick:
foreach($decode["item"] as $item) {
if($item->live == 1) {
...
} else {
...
}
}
If $item is not an object use $item['live'] instead.
P.S.: You should really turn error_reporting on. $option=>isLive is no valid syntax.
$t = 0;
$count = 0;
$arr = json_decode($json,true);
foreach($arr as $key=>$val)
{
print_r($key);
if($val['live'])
{
if($t == 0)
{
echo '<option value='.$val['name'].' selected>'.$val['name'].'</option>';
$t = 1;
}
else
{
echo '<option value='.$val['name'].'>'.$val['name'].'</option>';
}
}
else
{
echo $key.' not printed cause it hasn\'t live set to true';
}
$count++;
}
I have problem in deleting an element of array. Look:
<?php
session_start();
$i = 0;
$expected = $_GET['name'];
foreach($_SESSION['chart'] as $name)
{
if($name==$expected)
{
break;
}
$i++;
}
unset($_SESSION['chart'][$i]);
echo count($_SESSION['chart'])." ".$expected." ".$i;
//echo "<script>history.go(-1);</script>";
?>
I'm getting this output: 3 name 2.
I know that element in array exists with name 'name', but I can't unset it. Please help me.
Why not let PHP do the search?
<?php
session_start();
$key = array_search($_GET['name'], $_SESSION['chart']);
if ($key !== false) {
unset($_SESSION['chart'][$key]);
}
because you call unset out of foreach
try :
foreach($_SESSION['chart'] as $name)
{
if($name==$expected)
{
unset($name);
}
$i++;
}
You can make your intent clearer by using this form of foreach
foreach($_SESSION['chart'] as $idx=>$name)
{
if($name==$expected)
{
unset($_SESSION['chart'][$idx]);
break;
}
}
However, Till Helge Helwig's solution is better for this particular problem, but it's worth being aware that you don't need to maintain your own 'key' variable when using foreach.
In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).
I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.
foreach($potentialMatches as $potentialKey)
{
$searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
$searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
{
$keyword = $searchKeyWordsRow['keyword'];
$pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
$pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
foreach($picValue['keywords'] as $key = > $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++;
echo $picValue['match'];
}
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
echo $picValue['match'];
}
I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.
Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']
In that second foreach you need to call it by reference:
foreach($pictureKeywordArray as $key => &$picValue)
{ //^-- `&` makes it by reference
foreach($picValue['keywords'] as $key => $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++; //now updates what you want it to update
echo $picValue['match'];
}
}
}
foreach works on a copy of the data. You must use a reference to modify the original:
foreach ($foo as $i => &$f)
{
$f++;
}
unset($f); // important to do this if you ever want to reuse that variable later