how can i get multidimensional array values using foreach? - php

I want to use a multidimensional array in different functions.so i am making it as a global variable(array).i created a multidimensional array and made it as global to access in different function.now how can i get the values from it using foreach loop?
here is my code
$test=array(
array(
"input1"=>"v1",
"input2"=>"v2"),
array(
"input3"=>"v3",
"input4"=>"v4")
);
class testing
{
function testp()
{
global $test;
foreach($test as $key => $value)
{
echo $value;
}
var_dump($test);
echo is_array($test);
}
}
$obj = new testing();
$obj->testp();
i used is_array and var_dump to confirm whether its an array.
all are fine
and its shwoing Error suppression ignored. now how can i get the values from it?

It is array of arrays, what works for top order array, works further as well:
foreach($test as $key => $value)
{
foreach($value as $k => $v){
echo $v;
}
}
This will echo your values v1, v2, v3, v4 one after another.

More general answer:
public function visitArray($test)
{
foreach($test as $key=>$value)
{
if(is_array($value))
{
visitArray($value);
}
else
{
echo $value;
}
}
}
Edit
Don't know why you're looping over keys and values, if key isn't took into account

More easy & simple way to access array values within a array.
foreach($test as $array_value){
if(is_array($array_value)) {
foreach ($array_value as $value) {
echo $value.'<br>';
}
}
}

Related

Dynamically check for strings in a PHP array

EDIT: ten months later, I'm still back to this.. still can't figure it out :(
I can search for a string in an array no problem; this works:
if (in_array('animals', $value[tags])){
echo "yes";
}
But how can I check for a variable in the array? This doesn't seem to work:
$page_tag = 'animals';
if (in_array($page_tag, $value[tags])){
echo "yes";
}
I'm guessing I'm missing some simple syntax doodad?
The array is massive, so I'll try and show a sample of it. It is stored on a separate php file and "included" in other places.
global $GAMES_REPOSITORY;
$GAMES_REPOSITORY = array (
"Kitten Maker" => array (
"num" => "161",
"alt" => "Kitten Maker animal game",
"title" => "Create the kitten or cub of your dreams!",
"tags" => array ("animals", "feline", "cats", "mega hits"),
),
}
Here's a larger part of the code, to put into context. It pulls from the array of ~400 games, and pulls the ones with a specific tag:
function array_subset($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($page_tag, $value["tags"])){
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
return $newArray;
}
function array_copy($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset($GAMES_REPOSITORY);
$games_list = array_reverse($games_list);
Oh, an interesting hint. Elsewhere it DOES work using $_GET:
if (in_array($_GET[tagged], $value[tags])){
The in_array() function can check variables, so it is likely that your problem comes from somewhere else. Verify that you've defined your constant tags correctly. If it's not defined, it might not work depending on your PHP version. Some versions just assume that you wanted to write the string tags instead of a constant named tags.
Your code works. Here's a full example that I've tested that works well:
<?php
const tags = "tags";
$page_tag = 'animals';
$value = array('tags' => array("fruits", "animals"));
if (in_array($page_tag, $value[tags])){
echo "yes";
}
You have an array of arrays, so in_array() wont work as you have written it as that test for existence in an array, not a subarray. You may as well just loop through your arrays like this:
foreach($GAMES_REPOSITORY as $name =>$info) {
if(in_array($page_tag, $info['tags']))
{ whatever }
}
If that is not fast enough you will have to cache your tags by looping ahead of time and creating an index of tags.
I finally got it to work! I don't entirely understand why, but I had to feed the variable into the function directly. For some reason it wouldn't pull the variable from the parent function. But now it works and it even takes two dynamic variables:
function array_subset2($arr, $tag1, $tag2) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($tag1, $value['tags'])){
if (in_array($tag2, $value['tags'])){
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
}
return $newArray;
}
function array_copy2($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset2($GAMES_REPOSITORY, $page_tag, $featured_secondary_tag);

How to access associate array of array in php?

I'm from Perl but I'm beginner in PHP. I'm having following array
$rating_data = Array ("51" => Array (5,3,4,2));
I'm trying to access the each data using loop so I tried following
foreach ($keys as $rating_data)
{
foreach ($index as $rating_data[$keys])
{
echo "$index";
}
}
But the above one is not working. I have also tried the below one also,
$all_keys = array_keys($rating_data);
foreach ($keys as $all_keys)
{
foreach ($values as $all_keys)
{
echo "$values";
}
}
But I didn't get the output. It works if I hard code the keys like below:
$rating_data["51"][0];
How to fix this issue.?
You can get the key position and iter value ( sencod level ).
foreach($rating_data as $key => $values)
{
echo $key; // Output "51"
foreach($values as $value)
{
echo $value; // Output: iter1: "5", iter2: "3", iter3: "4", iter1: "2",
}
}
It should be as simple as below:
foreach($rating_data as $key => $values) {
echo $key;
foreach($values as $value) {
echo $value;
}
}
You seem to have your parameters the wrong way around in your foreach statements. I would advise a quick read through the foreach docs.

traversing an array in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loop an array of array
So I know how to traverse an array of even key => value (associative), but I have a weird array where I need to walk through it and print out values:
$object_array = array(
'type' => 'I am type',
array(
'property' => 'value',
'property_2' => 'value_2'
)
);
What I thought I could do is:
foreach($object as $key=>$vlaue){
//what now?
}
So as you can see I am lost, how do I walk through the next array?
You can try:
function traverse($array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
traverse($array);
continue;
}
echo $value;
}
}
foreach($object as $key=>$value){
if( is_array($value) ) {
foreach($value as $key2=>$value2) {
//stuff happens
}
} else {
//other stuff
]
}
Try:
foreach($object_array as $value) {
if(!is_array($value))
echo $value;
else {
foreach($value as $m)
echo $m;
}
}
Manual for foreach
In your for loop you could do:
if(is_array($object[$key]))
//process inner array here
It depends on how deep your arrays go, if you have arrays of arrays of arrays...and so on, a different method would be better, but if you just have one level this is a pretty simple way of doing it.
Well, you could do something like this:
foreach($object_array as $key=>$value)
{
if(is_array($value) {
foreach($value as $k=>$v) {
echo $k." - ".$v;
}
} else {
echo $key." - ".$value;
}
}
An alternative with array_walk_recursive():
function mydebug($value, $key) {
echo $key . ' => ' . $value . PHP_EOL;
}
array_walk_recursive($object_array, 'mydebug');
Handy if you doing something simple with the values (e.g. just echo ing).

Search multidimensional arrays for specific keys and output their data

I have following array construction: $array[$certain_key][some_text_value]
And in a while loop, I want to print the data from the array, where $certain_key is a specific value.
I know how to loop through multidimensional arrays, which is not the complete solution to this problem:
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
I do not want to loop the whole array each time, but only when $certain_key is matched.
EDIT: to be more exact, this is what I'm trying to do:
$array[$array_key][some_text];
while reading from db {
//print array where a value returned from the db = $array_key
}
while ($row = fetch()) {
if (isset($array[$row['db_id']])) {
foreach ($array[$row['db_id']] as $some_text_value => $some_text_values_value) {
echo ...
}
}
}
foreach ($array as $certain_key => $value) {
if($certain_key == $row['db_id']) {
foreach ($value as $some_text_value) {
echo "$v2\n";
}
}
}
You mean like
foreach($array[$certain_key] as $k => $v)
{
do_stuff();
}
?
Maybe you're looking for array_key_exists? It works like this:
if(array_key_exists($certain_key, $array)) {
// do something
}
<?php
foreach ($a as $idx => $value) {
// replace [search_value] with whatever key you are looking for
if ('[search_value]' == $idx) {
// the key you are looking for is stored as $idx
// the row you are looking for is stored as $value
}
}

How to foreach through part of an objects member variables that are arrays?

I am trying to create a foreach that will go through some variables within an object.
At the moment it is just
class jabroni
{
var $name = "The Rock";
var $phrases = array ("The rock says", "Im gonna put the smackdown on you", "Bring it on jabroni");
var $moves = array ("Clothes line", "Pile driver", "Reverse flip");
}
I tried doing this:
$jabroni = new jabroni()
foreach ($jabroni as $value)
{
echo $value->phrases;
echo $value->moves;
}
However nothing gets printed.
Any ideas if what I am trying to achieve is possible, I have that gut feeling that its not and that I will have to just do individual foreach statements for each object member variable that is an area?
Thanks for your time!
You are doing wrong the loop.. You have one object, not an array of objects. so the correct way should be..
$jabroni = new jabroni();
foreach ($jabroni->phrases as $value)
{
echo $value;
}
foreach ($jabroni->moves as $value)
{
echo $value;
}
foreach ($jabroni->phrases as $value) {
echo $value;
}
foreach ($jabroni->moves as $value) {
echo $value;
}
You can do it in nested foreach loops. This will be easy instead of going for two for loops seperatley
foreach ($jabroni as $keys => $values)
{
if ($keys == 'phrases' || $keys == 'moves') {
foreach ($values as $value) {
echo $value;
}
}
}

Categories