0

I am using Codeigniter 3 and getting data from an API. The API returns the below after I pass the origin json data through, $myArray = json_decode($theBody, true);

array(2) {
  ["status"]=>
  string(7) "failure"
  ["message"]=>
  array(2) {
    ["entry_name"]=>
    string(61) "The entry_name field must be at least 8 characters in length."
    ["entry_body"]=>
    string(61) "The entry_body field must be at least 8 characters in length."
  }
}

I now want to pass that error message via flashdata to my view which I do as follows:

// VIEW FILENAME: new.php
$this->session->set_flashdata('message', $myArray);

In my view, when I run this:

       echo "<pre>";
        echo var_dump($this->session->flashdata('message'));
        echo "</pre>";

I get the expected output (same as above):

   array(2) {
  ["status"]=>
  string(7) "failure"
  ["message"]=>
  array(2) {
    ["entry_name"]=>
    string(61) "The entry_name field must be at least 8 characters in length."
    ["entry_body"]=>
    string(61) "The entry_body field must be at least 8 characters in length."
  }
}

However, how can I iterate through the array?

How can I refer to the contents of ["status"] and ["message"]

Any pointers appreciated.

2 Answers 2

2

Take the values in the variable and navigate to the array values as follows:

$flashData = $this->session->flashdata('message');
$status = $flashData['status'];
$message = $flashData['message'];
$entry_name = $flashData['message']['entry_name'];
$entry_body = $flashData['message']['entry_body'];

Check the array How its coming through, If Zero indexed add [0] front of the array pointer. (Ex: $flashData[0]['entry_name'])

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

Comments

2

you can access flashdata fields by its key since its an associative array.

$flashdata = $this->session->flashdata('message');
$status = $flashdata['status'];

As message is an array, iterate through array to fetch its value.

foreach($flashdata['message'] as $key => $value){
     echo $value;
}

2 Comments

Add some useful explanation to your answer
thank you for your suggestion. I have edited my answer.

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.