Iterate through array and get key and value [duplicate] - php

This question already has answers here:
How to loop through an associative array and get the key?
(12 answers)
Closed 8 years ago.
I need to iterate through a dynamic array. The array will look something like the following:
Array
(
[2010091907] => Array
(
[home] => Array
(
[score] => Array
(
[1] => 7
[2] => 17
[3] => 10
[4] => 7
[5] => 0
[T] => 41
)
[abbr] => ATL
[to] => 2
)
[away] => Array
(
[score] => Array
(
[1] => 0
[2] => 7
[3] => 0
[4] => 0
[5] => 0
[T] => 7
)
[abbr] => ARZ
[to] => 2
)
[weather] =>
[media] => Array
(
[tv] => FOX
[sat] => 709
[sathd] => 709
[radio] => Array
(
[home] => 153
[away] => 90
)
)
[bp] => 13
[yl] =>
[qtr] => Final
[down] => 0
[togo] => 0
[clock] => 00:26
[posteam] => ARZ
[note] =>
[redzone] =>
[stadium] => Georgia Dome
)
I need it to be dynamic and for testing purposes, I need to be able to call it via:
echo "Key: $key; Value: $value<br />\n";
I'm going to later take this information and place it into a mysql database, but for now, I need to brush up on arrays and figure out how to format the data.
Any help is appreciated.

I´d go for a recursive function: If a value is an array, call it again and otherwise display the key / value pair.
Something like (not tested):
function display_array($your_array)
{
foreach ($your_array as $key => $value)
{
if is_array($value)
{
display_array($value);
}
else
{
echo "Key: $key; Value: $value<br />\n";
}
}
}
display_array($some_array);

Related

Echo arrays in foreach loop codeigniter

I've been using codeigniter for years but there's a really big gap in between so i always find myself in situations where i forgot how to do things and its almost midnight here so my brain isn't working fast. Can someone show me how to echo the array i have and explain to me how they are processed in the foreach loops?
I have this code in my model to take the rows in 2 tables.
public function tag_genre(){
$result['tag'] = $this->db->get('tags')->result_array();
$result['genre'] = $this->db->get('genre')->result_array();
return $result;
}
And I have this in my controller
public function view_publish_story(){
$data = array('tag_genre' => $this->story_model->tag_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
I used print_r in my view and this is the result. Seeing this just confuses me more. It's been atleast 2 years since i even dealt with foreach loops.
Array ( [tag] => Array ( [0] => Array ( [tag_id] => 1 [tag_name] =>
LitRPG ) [1] => Array ( [tag_id] => 2 [tag_name] => Virtual Reality )
[2] => Array ( [tag_id] => 3 [tag_name] => Cyberpunk ) [3] => Array (
[tag_id] => 4 [tag_name] => Reincarnation ) [4] => Array ( [tag_id] =>
5 [tag_name] => Summoned Hero ) [5] => Array ( [tag_id] => 6
[tag_name] => Martial Arts ) [6] => Array ( [tag_id] => 7 [tag_name]
=> Slice of Life ) [7] => Array ( [tag_id] => 8 [tag_name] => Overpowered ) [8] => Array ( [tag_id] => 9 [tag_name] => Non-Human )
[9] => Array ( [tag_id] => 10 [tag_name] => Anti-hero ) ) [genre] =>
Array ( [0] => Array ( [genre_id] => 1 [genre_name] => action ) [1] =>
Array ( [genre_id] => 2 [genre_name] => adventure ) [2] => Array (
[genre_id] => 3 [genre_name] => comedy ) [3] => Array ( [genre_id] =>
4 [genre_name] => Drama ) [4] => Array ( [genre_id] => 5 [genre_name]
=> Fantasy ) [5] => Array ( [genre_id] => 6 [genre_name] => Historical ) [6] => Array ( [genre_id] => 7 [genre_name] => Horror ) [7] => Array
( [genre_id] => 8 [genre_name] => Psychological ) [8] => Array (
[genre_id] => 9 [genre_name] => Romance ) [9] => Array ( [genre_id] =>
10 [genre_name] => Sci-fi ) [10] => Array ( [genre_id] => 11
[genre_name] => Mystery ) [11] => Array ( [genre_id] => 12
[genre_name] => Tragedy ) [12] => Array ( [genre_id] => 13
[genre_name] => Short Story ) [13] => Array ( [genre_id] => 14
[genre_name] => Satire ) ) )
I've been looking at various questions regarding arrays from assoc to multidimensional and other stuff. Then i finally visited php manual for foreach loop and i finally was able to echo the array. The problem now is that although it echoes my array it also has an error for each, i can probably fix the error part by declaring it as a defined variable. My question is, is there any other better way? or any improvement on how i made my array to make it cleaner or easier to print?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo $values['tag_name'];
}
}
UPDATE: i changed the way i made the array.
This is now my model:
public function get_tags(){
$query = $this->db->get('tags')->result_array();
foreach($query as $row){
$result[$row['tag_id']] = $row['tag_name'];}
return $result;
}
public function get_genre(){
$query = $this->db->get('genre')->result_array();
foreach($query as $row){
$result[$row['genre_id']] = $row['genre_name'];}
return $result;
}
and my controller:
public function view_publish_story(){
$data = array('tag' => $this->story_model->get_tags(), 'genre' => $this->story_model->get_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
and in my view:
<tr>
<div class="form-group">
<td><label for="genre">Genre</label></td>
<?php
foreach($genre as $genre_id => $genre_name){
echo "<td><label class='checkbox-inline'><input type='checkbox' value=''>".$genre_name."</label><td>";
}
?>
</div>
</tr>
My problem now is that, how do i fit all these into my table? I just ruined my table right now since i echoed them all in a single line. How do i do it so that it is printed in 3 columns?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo '<pre>';
echo $values['tag_name'];
}
}
this will format your array in a way you can read it and understand it.

Looping thought multilevel array php [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 7 years ago.
I have an array in php that looks like this:
print_r($myArray);
Array (
[0] => Array
(
[age] => 1
[time] => 2
[name] => james
[size] => 12
[hieght] => 13
)
[1] => Array
(
[age] => 3
[time] => 1
[name] => tim
[size] => 12
[hieght] => 13
)
[2] => Array
(
[age] => 1
[time] => 2
[name] => john
[size] => 132
[hieght] => 4
)
[3] => Array
(
[age] => 1
[time] => 2
[name] => logan
[size] => 12
[hieght] => 11
)
)
Im trying to loop though every item and save each "size" in a new array. I have looked into solutions for pulling out the "size" from each inner array but cant seem to get it right:
$all_sizes = array();
foreach($myArray as $value) {
foreach($value as $key => $val) {
if($key == "size") {
}
}
}
I am new to PHP so im struggling on the proper syntax for this situation.
Remove the next foreach()
$all_sizes = array();
foreach($myArray as $value => $getSize) {
$all_sizes[] = $getSize['size'];
}
print_r($all_sizes);

Flatten Nested Array to a certain Key

I have a data structure like this
Array
(
[0] => Array
(
[actionResult] => Array
(
[show_page] => Array
(
[15] => Array
(
[section_page_id] => 15
[metadata_id] => 62
[section_id] => 7
[display_order] => 0
[current_layout] => 15
[behaviors] => a:1:{i:0;a:1:{i:0;a:0:{}}}
[options] => a:1:{s:13:"defaultLayout";i:63;}
[section_title] => Ask Study
)
[16] => Array
(
[section_page_id] => 16
[metadata_id] => 66
[section_id] => 7
[display_order] => 1
[current_layout] => 16
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:67;}
[section_title] => Ask Study
)
[17] => Array
(
[section_page_id] => 17
[metadata_id] => 69
[section_id] => 7
[display_order] => 2
[current_layout] => 17
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:70;}
[section_title] => Ask Study
)
[18] => Array
(
[section_page_id] => 18
[metadata_id] => 72
[section_id] => 7
[display_order] => 3
[current_layout] => 18
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:73;}
[section_title] => Ask Study
)
)
)
)
[1] => Array
(
[actionResult] => Array
(
[view_page] => 18
)
)
)
What i need is the ability to flatten this to an array structure to a point where it stops at "actionResult" where all the actionResult will become ONE array rather than nested like this...
How can I go about by doing this in PHP???
if i have understood what you want correctly this should work:
$arr2=array();
foreach($arr as $tmp){
foreach($tmp as $actionRequest){
foreach($actionRequest as $key=>$val){
$arr2[$key]=$val;
}
}
}
where $arr is what you already have and $arr2 will be an array including 2 values , Show_Page and view_page
Best solution is:
$new_arr = array_map(function ($a) {
return $a['actionResult'];
}, $old_arr);

php echo nested object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Able to see a variable in print_r()'s output, but not sure how to access it in code
I want to 'echo' a little bit more nested object.
I saw several posts to this question - but this is freaking me out.
I got an Array/Object named 'arrResult' and the print_r(arrResult) output is:
Array
(
[status] => stdClass Object
(
[code] => 0
[message] => Success
)
[result] => Array
(
[0] => stdClass Object
(
[base] => stdClass Object
(
[id] => 3
[created] => 2012-11-11 12:11:07
[start] => 2012-11-11
)
[pos] => Array
(
[0] => stdClass Object
(
[id] => 4
[invoices_id] => 3
[article_id] => 1
[quantity] => 1
[unit] => Monate
[pos_txt] => Paketname
)
)
[summ] => stdClass Object
(
[net] => 2.52
[discount] => 0
[tax] => 0.47899159663865
[gross] => 3
[rounded_net] => 2.52
)
)
[1] => stdClass Object
(
[base] => stdClass Object
(
[id] => 2
[created] => 2012-11-11 12:10:39
[start] => 2012-11-11
)
[pos] => Array
(
[0] => stdClass Object
(
[id] => 3
[invoices_id] => 2
[article_id] => 2
[quantity] => 1
[unit] => Monate
[pos_txt] => Paketname2
)
)
[summ] => stdClass Object
(
[net] => 5.04
[discount] => 0
[tax] => 0.95798319327731
[gross] => 6
[rounded_net] => 5.04
)
)
)
)
I want to echo all [pos].
Something like 'echo arrResult[result][0][pos][0]->pos_txt', 'echo arrResult[result][0][pos][1]->pos_txt',...
I thought about this:
foreach ((array)$arrResult['result'] as $key => $contract) {
foreach ($contract as $key => $objPos){
echo $objPos->pos_txt;
}
}
My brain doesn't get it.
Can someone help me with this?
You can use
echo "<pre>";
foreach(array_map(function($v){ return $v->pos ;}, $data['result']) as $list)
{
foreach($list as $objPos)
echo $objPos->pos_txt,PHP_EOL;
}
Output
Paketname
Paketname2
See Live Demo
Use xdebug extension, it's something what you must have for development anyway, it slightly changes how var_dump works and I believe it will solve your problem
see xdebug documentation
$num = count($arrResult['result']);
for ($i=0; $i <= $num; $i++) {
echo $arrResult['result'][$i]->pos[0]->pos_txt;
}

comparing array value from multidimensional array with index

I have a multidimensional array that loks lik this:
Array
(
[0] => Array
(
[name] => >chr1:2198584545754_genome_1000+
[score] => 511
[hit] => 50
)
[1] => Array
(
[name] => >chr2:2198581212154_genome_1000+
[score] => 620
[hit] => 80
)
[2] => Array
(
[name] => >chr3:2115151215754_genome_1000+
[score] => 666
[hit] => 90
)
[3] => Array
(
[name] => >chr4:2198584545754_genome_1000+
[score] => 750
[hit] => 50
)
[4] => Array
(
[name] => >chr5:1218455145754_genome_1000+
[score] => 800
[hit] => 100
)
[5] => Array
(
[name] => >chr6:1231354645454_genome_1000+
[score] => 850
[hit] => 110
)
[6] => Array
(
[name] => >chr7:1231213211134_genome_1000+
[score] => 900
[hit] => 120
)
)
I have a foreach loop which will loop through each letter of a random sequence and use the index to give each letter a number value.
If the value of ['hit'] matches the index value of the random sequence
i want to insert a function.
I cannot figure this out. I think my problem is in callng each value of ['hit'] and comparing with index. Does anyone know how to do this ?
thanks
To put DaveRandom's comment into an answer (with minor amends):
foreach ($outerArray as $index => $innerArray)
{
if($innerArray['hit'] === $index)
{
doSomething();
}
}
#DaveRandom - feel free to delete or re-post this as your own answer if I'm posting out of turn here...
foreach ($array as $key) {
if ($key['hit'] == $index)
{
// you function or logic here
}
}

Categories