-1

I have an array like this:

array (size=2)
  'status' => string 'ok' (length=2)
  'data' => 
    array (size=5)
      'sort_data' => 
        array (size=2)
          'sort_column' => string 'order_item_id' (length=13)
          'sort_order' => string 'asc' (length=3)

Now I coded this for getting sort_column and it's value and also sort_order and it's value:

$status = $response['status'];

if($status == 'ok'){
    $nums = count($response['data']['sort_data']); //retrieves 2
    for($i=0; $i<=$nums; $i++){
        foreach($response['data']['sort_data'][$i] as $key=>$value){
            echo $key."=".$value;
        }
    }
}

But I get these errors:

Notice: Undefined offset: 0 on line 6

Warning: Invalid argument supplied for foreach() on line 6

Line 6:

foreach($response['data']['sort_data'][$i] as $key=>$value){

So what is going wrong here?

How can I get the contents of sort_data within this foreach properly?

UPDATE #1:

Array
(
    [status] => ok
    [data] => Array
        (
            [sort_data] => Array
                (
                    [sort_column] => order_item_id
                    [sort_order] => asc
                )
halfer
  • 19,824
  • 17
  • 99
  • 186
  • `for($i=0; $i<=$nums; $i++)` will give you an off by one error. Besides that, the error is telling you exactly the problem. You supply a string value to the foreach. – Remy Jun 25 '21 at 07:15
  • @JohnLobo I put this project out of laravel, it is now written in pure PHP –  Jun 25 '21 at 07:30
  • echo "
    "; print_r($response);  exit(); try this
    – John Lobo Jun 25 '21 at 07:31
  • I added an **update #1** –  Jun 25 '21 at 07:32
  • @tejoslaeslio can you post expected output as well – John Lobo Jun 25 '21 at 07:38
  • @JohnLobo I need to store each of these into individual variables such as `$sort_column` and `$sort_order`. –  Jun 25 '21 at 07:39
  • @JohnLobo That's why I decided to use for loop so I could say `for($i=0; $i<=$nums; $i++){ foreach($response['data']['sort_data'][$i] as $key=>$value){ $response['data']['sort_data'][$key] = $response['data']['sort_data'][$value]; } }` –  Jun 25 '21 at 07:41
  • Why are you imploding these paired values with `=`? What is the point? It looks like mutation for mutation's sake. XY Problem? Also, it's all associative keyed, so you can only store a max of one column sorting rule. – mickmackusa Jun 25 '21 at 07:42

1 Answers1

0

I think no need of for loop

  if($status == 'ok'){
       
      $sort_column=$response['data']['sort_data']['sort_column'];
      $sort_order=$response['data']['sort_data']['sort_order'];
    }
John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • Then it will give me two results: `sort_column=order_item_id` & `sort_order=asc`. I need to store each of these into indivisual variables such as `$sort_column` and `sort_order`. –  Jun 25 '21 at 07:23
  • @tejoslaeslio.updated my answer – John Lobo Jun 25 '21 at 07:42