I am working on my first PHP Layout from my existing HTML. I am running in to trouble. I hope stackoverflow can help
I have 3 arrays
$parent = array('1' => 'parent1' , 'parent2' , 'parent3' , 'parent4' , );
$child = array('1' => 'child1' , 'child2' , 'child3' , 'child4' , );
$content = array('1' => 'content1' , 'content2' , 'content3' , 'content4' , );
I am trying to use them to make a repeating list which will include {$parent}, {$child}, and {$content} like the following..
<?php
echo "<h1 id='js-overview' class='page-header'>$parent</h1>"
echo "<h3 id='js-fotopia'>$child</h3>"
echo "<p>$content</p>"
?>
but i need to run this for each of my variables. How do I write the statement? also how can I set it up so that the child and child content are also repeating. like in the pic
See the pic to understand my layout that i need to keep repeating as long as there are variables filled out... Please ask questions if i am not making since rather than skipping... I need php guidance.
I think your structure is a bit off. Instead of 3 arrays, why not combine them into one? It's a little unclear how the parent/child/content relationship you have is setup, but here's a shot:
$arr = array(
'parent1' => array(
'child1' => array(
'content' => 'This is your content for child 1',
),
'child2' => array(
'content' => 'This is your content for child 2',
),
),
'parent2' => array(
'child1' => array(
'content' => 'This is your content for child 1 inside of parent 2',
)
),
);
Then you can just foreach over the array, and foreach over the children:
foreach($arr as $parent) {
foreach($parent as $childName => $child) {
echo $child['content'];
}
}
You can add more keys into the children array if you need more structure to your content.
Perhaps something like this?
for($i=1; $i<=count($parent); $i++){
echo "<h1 id='js-overview' class='page-header'>$parent[$i]</h1>"
echo "<h3 id='js-fotopia'>$child[$i]</h3>"
echo "<p>$content[$i]</p>"
}
Alternatively you could use a foreach and assuming the keys line up like this syntax
foreach (array_expression as $key => $value)
statement
Alternatively to that you could construct 1 2D array that stores the parent, child and content all in 1 row.
Related
I want to remove an item from an array. I can write this:
$item = array(
'id' => 1
'name' => 'name'
);
$item2 = $item;
unset($item2['id']);
$names[] = $item2;
but the last 3 lines are somewhat "cumbersome", soo un elegant. Can it be solved without creating $item2 ? Something like:
$item = array(
'id' => 1
'name' => 'name'
);
$names[] = array_ignore_index('id', $item);
From your codes, I can see that you are trying to get the names[] from item array. One possible simple solution for this specific scenario:
For example IF you have :
$items = array(
array(
//this is your item 1
'id' => 1,
'name' => 'name1'
),
array(
//this is item 2
'id' => 2,
'name' => 'name2'
)
);
and you want to retrieve the names in the names array.
You can just do:
$names = array_column($items, 'name');
It will return:
Array
(
[0] => "name1"
[1] => "name2"
)
Please note this solution is best fit for this specific scenario, it may not fit your current scenario depending.
The shortest out of the box solution is to create a diff of the array keys:
$names[] = array_diff_key($item, array_flip(['id']));
See http://php.net/array_diff_key.
function array_ignore_index($id,$item){ ///function
unset($item[$id]);
return $item;
}
$a=array('id'=>1,
'name'=>'name');
$b=array_ignore_index('name',$a);
echo $b['name']; //create error id is not present
Here is the code for required operation..
You can use unset array column
Code is
unset($item['id']);
To test it
print_r($item);
can someone tell me what is this code doing, As im new to Yii, learning about it.. im not able to understand few things.. Here is the code..
$allmsg = LogMsg::model()->findAll($criteria); //
$dataArr = array();
if (isset($allMsg) && sizeof($allMsg) != 0):
foreach ($allMsg as $msg) {
$dataArr[$msg->date][] = array( // array?
'category' => $msg->category, // what is that 'category' a variable or something else? and $msg->category, is what?
'time' => $msg->time,
'date' => $msg->date,
'user' => $msg->name
);
} endif;
$this->render('index', array(
'data' => $dataArr ) //what is that 'data'?
);
My question is, what is this line of code doing exactly in foreach loop
$dataArr[$msg->date][] = array(
'category' => $msg->category,
and here is second code... which has something like that..
$allCat = Categories::model()->findAll($criteria);
$catArr=array();
if(isset($allCat) && sizeof($allCat)!=0):
foreach ($allCat as $catModel) {
$catArr[$catModel->id] =$catModel;
}
endif;
return $catArr;
so what is this line doing in this code in foreach loop, what is different between these two lines in first and second code..
$catArr[$catModel->id] =$catModel;
last thing.. what is it
public static function getID($category)
{
$arr = array(
'ast'=>1, // what are these things? from where are they coming? db?
'fp'=>5, //
'per'=>3,
'ts'=>6,
'lg'=>3
);
return isset($arr[$category])?$arr[$category]:null; //Ternary - Condensed if/else statement
}
So as per your first question.
$dataArr[$msg->date][] = array(
'category' => $msg->category,
$allMsg is the active record object which u get through the db query. This object is traversed in a loop and each row is "$msg".
Hence you can access the attributes of the model through the $msg->category. 'category' here is the attribute of the model.
this is creating multidimensional array.
Your first question
$dataArr[$msg->date][] = array(
'category' => $msg->category,
will generate output like
[2016-03-04] => Array
(
[0] => Array
(
[category] => abc
)
)
And your second question
$catArr[$catModel->id] =$catModel;
will genrate output like
array(
[0] =>1,
[1] => 2,
[2] => 3,
)
Not tested.
I think, your question is not about Yii. You should read about arrays of PHP first. In the code multidimensional array have been used. It means that the array can contain another array as value.
I'm writing a php web application where I have a nested array which looks similar to the following:
$results = array(
array(
array(
'ID' => 1,
'Name' => 'Hi'
)
),
array(
array(
'ID' => 2,
'Name' => 'Hello'
)
),
array(
array(
'ID' => 3,
'Name' => 'Hey'
)
)
);
Currently this means that when I want to use the ID field I have to call $results[0][0]['ID'] which is rather inefficient and with an array of over several hundred records becomes messy quickly. I would like to shrink the array down so that I can call $results[0]['ID'] instead.
My understanding is that a function that uses a foreach loop to iterate through each row in the array and change the format would be the best way to go about changing the format of the $results array but I am struggling to understand what to do after the foreach loop has each initial array.
Here is the code I have so far:
public function filterArray($results) {
$outputArray = array();
foreach ($results as $key => $row) {
}
return $outputArray;
}
Would anyone be able to suggest the most effective way to achieve what I am after?
Thanks :)
Simply use call_user_func_array as
$array = call_user_func_array('array_merge', $results);
print_r($array);
Demo
I am trying to add up a specific variable (gq_numplayers) and display it. How can I do that if the arrays are in an array?
I am using GameQ (https://github.com/Austinb/GameQ/) if you don't understand what is going on.
EDIT:
var_dump ($results);
http://pastebin.com/BSeeWMEb
<?php
// Include the main class file
require '../GameQ.php';
// Define your servers,
// see list.php for all supported games and identifiers.
$servers = array(
array(
'id' => 'server 1',
'type' => 'css',
'host' => '216.52.148.30',
),
array(
'id' => 'server 2',
'type' => 'css',
'host' => '216.52.143.83',
),
array(
'id' => 'server 3',
'type' => 'teamspeak3',
'host' => 'voice.xenogamers.org:8730',
)
);
// Init the class, only need this once
$gq = new GameQ();
$gq->addServers($servers);
//optional settings
$gq->setOption('timeout', 3); // Seconds
$gq->setOption('debug', TRUE);
// You can optionally specify some output filters,
// these will be applied to the results obtained.
$gq->setFilter('normalise');
// Send requests, and parse the data
$results = $gq->requestData();
//make total
$total = array_sum(?!?!?!??!?!?);
echo $results['server 1']['gq_numplayers'];
?>
Just loop through the servers and add the number of players to a running total.
$num_players = 0;
foreach ($results as $server) {
$num_players += (int)$server['gq_numplayers'];
}
If you have $ArrayB inside $ArrayA, then you need a loop. Loop through $ArrayA with foreach like this:
foreach ($ArrayA as $item) {
}
Inside that loop, you need to add the code to operate on $item. So each time the loop iterates, $item will be the next item in the array! You can add them all up with a variable declared before entering the loop such as $counter.
But I am also noticing you indicated this:
echo $results['server 1']['gq_numplayers'];
That is NOT an array in an array. That is a single two-dimensional array. So my answer wouldn't even apply directly to it. You'd have to change the loop somewhat.
You could try adding it yourself via array_walk().
I'm not sure about the $results structure after the requestData() call but let's assume it looks like the sample array below:
<?php
$results= array(
array(
'something' => 'text',
'gq_numplayers' => 1,
),
array(
'something' => 'text',
'gq_numplayers' => 2,
),
array(
'something' => 'text',
'gq_numplayers' => 3,
),
);
$total=0;
array_walk($results,function($value,$key) use(&$total) {
$total+=(int)$value['gq_numplayers'];
});
print $total."\n";
What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.