eldan88 Posted May 19, 2013 Share Posted May 19, 2013 Hey, I am trying to figure out how I can pull an array that is within an array. I have trying doing that but not getting any luck. Below is an example code that I am trying to work with, but its only returning the letter "G" Any suggestions? $name_array = array("dog",array("cat")); echo $name_array[0][2]; Quote Link to comment Share on other sites More sharing options...
Strider64 Posted May 19, 2013 Share Posted May 19, 2013 (edited) <?php $name_array_original = array ( 0 => array('animal' => 'dog'), 1 => array('animal' => 'cat'), 2 => array('animal' => 'tiger') ); $name_array = array ( 0 => array('animal' => 'dog' , 'name' => 'Snoopy'), 1 => array('animal' => 'cat', 'name' => 'Garfield'), 2 => array('animal' => 'tiger', 'name' => 'Tony') ); // Name sorting function: function name_sort($x, $y) { return strcasecmp($x['name'], $y['name']); } echo '<h2>Original Array</h2><pre>' . print_r($name_array_original, 1) . '</pre>'; uasort($name_array, 'name_sort'); echo '<h2>Array Sorted By Name</h2><pre>' . print_r($name_array, 1) . '</pre>'; foreach ($name_array_original as $original) { foreach ($original as $key => $value) { echo '<p>Key = ' . $key . '<br>Value = ' . $value . '</p>'; } } Edited May 19, 2013 by Strider64 Quote Link to comment Share on other sites More sharing options...
Barand Posted May 19, 2013 Share Posted May 19, 2013 $name_array[0] is the string "dog", so $name_array[0][2] is the third letter of "dog" Quote Link to comment Share on other sites More sharing options...
Eiseth Posted May 20, 2013 Share Posted May 20, 2013 Try using is_array() to check whether the next element is an array foreach ($name_array as $arr) { // only arrays will process if (is_array($arr)) { $arrays = $arr; } } print_r($arrays); // array([0]=>'cat') Quote Link to comment Share on other sites More sharing options...
haku Posted May 20, 2013 Share Posted May 20, 2013 echo $name_array[1][0]; Quote Link to comment Share on other sites More sharing options...
AbraCadaver Posted May 21, 2013 Share Posted May 21, 2013 echo $name_array[1][0]; Yes, get used to print_r() print_r($name_array); /* Array ( [0] => dog [1] => Array ( [0] => cat ) ) */ Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.