0

I'm trying to print array. All code working fine with foreach loop. But I'm trying to print with associated keys. Is it possible?

Example: key['user_id'] this will print all user_id from array. is it possible? please help me thanks

Array
(
    [Post1] => Array
    (
        [id] => 1
        [title] => hi
    )
    [Post2] => Array
    (
        [0] => Array
            (
                [user_id] => 1
            )
        [1] => Array
            (
                [user_id] => 2
            )
    )
    [Post3] => Array
    (
        [0] => Array
            (
                [user_name] => 1
            )
    )
)

Here is my PHP code:

foreach($post as $key => $value) {
    foreach($value as $print => $key) {
        if (is_array($key)){
            foreach($key as $print2 => $key2) {
                echo "<br>".$key2;
            }
        }else{
            echo "<br>".$key;
        }
    }
}
no_freedom
  • 1,963
  • 10
  • 30
  • 48
  • Given example is not clear enough ? – Shakti Singh Jun 13 '11 at 11:17
  • @Shakti Singh My array display all records from array. I don't want to print whole array. I just want to print particular data from array. suppose I want to print `username and userid' form array. is it possible? – no_freedom Jun 13 '11 at 11:25
  • possible duplicate of [How to search by key=>value in a multidimensional array in PHP](http://stackoverflow.com/questions/1019076/how-to-search-by-key-value-in-a-multidimensional-array-in-php) – Shakti Singh Jun 13 '11 at 11:42
  • What should the output of the above example look like? –  Jun 13 '11 at 19:40
  • Use `print_r` or `var_dump()`. – Alp Jun 13 '11 at 11:19

2 Answers2

1

I'm trying to print array. All code working fine with foreach loop. But I'm trying to print with associated keys. Is it possible?

You can easily use recursion for such a problem. You can use something along the lines of:

function printValuesByKey($array, $key) {
    if (!is_array($array)) return;
    if (isset($array[$key])) 
        echo $key .': '. $array[$key] .'<br>';
    else
        foreach ($array as $v)
            printValuesByKey($v, $key);
}

In your example:

printValuesByKey($array, 'user_id');

will print:

user_id: 1
user_id: 2
Shoe
  • 74,840
  • 36
  • 166
  • 272
1

You can print_r to achive the same results you want with your triple for each.

dynamic
  • 46,985
  • 55
  • 154
  • 231