0

This is my sample array value returned

array:3 [▼
  "Status" => array:1 [▼
    0 => "200"
  ]
  "Data" => array:1 [▼
    0 => array:1 [▼
      0 => array:2 [▼
        "sellerId" => array:1 [▼
          0 => "TEST01"
        ]
        "currency" => array:1 [▼
          0 => "USD"
        ]
      ]
    ]
  ]
  "Date" => array:1 [▼
    0 => "Dec 31 2019"
  ]
]

My sample code to retrieve the value from the array above

foreach($json_array as $key => $json) {
            if($key == "Status") {
                $status = $json[0];
            } else if ($key == "Date") {
                $date = $json[0];
            } else {           
                dd($json[0][0]['sellerId'][0]);
            }
        }

I am using the method above to retrieve the value from multidimensional array. Is there any better approaches that i can use to achieve my way?

3
  • Nope, that's pretty much it. Or maybe something like: if (!empty($json_array[0]['Status']) $status = $json_array[0]['Status']; etc. That allows you to compare each of three expected key-values in three lines of code. If you don't know whether 'Status' is going to be the 0th or the 1st etc. array element, maybe you need to restructure the input array (if you can) to something that can be more consistent. Commented Dec 30, 2019 at 17:35
  • @UncaAlby hi, the data returned all in fixed sequence. There will be no any extra value or details added in. I thought there's better way to achieve it haha Commented Dec 30, 2019 at 17:43
  • @iizno's answer is correct. The "array:3" threw me off, I was expecting a numeric array of arrays, but that's not the case. You may still want to use if(!empty({expr}) just in case the input stream happens to be missing an expected key/value. Commented Dec 30, 2019 at 18:19

1 Answer 1

1

Just do :

$status = $json_array['Status'];
$date   = $json_array['Date']; 

Maybe you should add some context to your question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.