Monday, 27 August 2018

Multidimensional array confused in PHP with foreach error

what is use of multidimensional array(2D,3D or what is the limit in multidimensional array) and foreach()? foreach() is use for printing values inside array? In case of multidimensional array why nested loop is important?
Errors:
Notice: Array to string conversion in C:\xampp\htdocs\example\basic\foreach2.php on line 9 Arrayarray(3) { [0]=> int(4) [1]=> int(5) [2]=> int(7) }
Notice: Array to string conversion inC:\xampp\htdocs\example\basic\foreach2.php on line 11
$items = array(1,2,3,
      array(4,5,7
     ),
     8,54,4,5,5);
foreach($items as $key => $value)
{
   echo $value;
   var_dump($value);
   echo $key ."pair match".$value . "<br>";
}

HOW do I access this array?
      $a_services = array(
        'user-login' => array(
          'operations' => array(
            'retrieve' => array(
              'help' => 'Retrieves a user',
              'callback' => 'android',
              'file' => array('type' => 'inc', 'module' => 'android_services'),
              'access callback' => 'services',
              'args' => array(
                array(
                  'name' => 'phone_no',
                  'type' => 'string',
                  'description' => 'The uid ',
                  'source' => array('path' => 0),
                  'optional' => FALSE,
                ),
              ),
            ),
          ),
         ),
        );
  print_r($a_services['$android_services ']['user-login']['operations']['retrieve']['callback']);
 print_r($a_services['$android_services ']['user-login']['operations']['retrieve']['callback']['args']['name']);

Error 1. Notice: Array to string conversion 2. Undefined index: $android_services 3. How to print with help of foreach 4. above array is 4 dimensional??????

To loop through this kind of array you need some sort of recursiveness.
I usually call a function inside the for each. the function tests whether the current element is an array. If so the functions call itself. If not the function does whatever (echo the value in your example).
Something like:
foreach($a_services as $key => $value) {
    do_your_thing($value);
}

function do_your_thing($recvalue)
{
    if (is_array($recvalue))
    {
        foreach($recvalue as $key => $value)
        {
            do_your_thing($value);
        }
    }
    else
    {
        echo $recvalue;
    }
    return $recvalue;
}

0 comments:

Post a Comment