3

my array

$data1 = array(
        array(
                'title' => 'My title',
                'name' => 'My Name',
                'date' => 'My date'
        ),
        array(
                'title' => 'Another title',
                'name' => 'Another Name',
                'date' => 'Another date'
        )
);

I want to add one array 'status' => 1 all associative array :

$data = array(
        array(
                'title' => 'My title',
                'name' => 'My Name',
                'date' => 'My date',
                'status' => 1

        ),
        array(
                'title' => 'Another title',
                'name' => 'Another Name',
                'date' => 'Another date',
                'status' => 1
        ),
        array(
                'title' => 'second title',
                'name' => 'second Name',
                'date' => 'second date',
                'status' => 1
        )
);
1
  • 1
    You'd probably implement a foreach loop and iterate over your outer array, or apply an array_walk callback on it. Commented Mar 20, 2018 at 10:47

4 Answers 4

6

Simple foreach() wiil do the job:-

foreach($data1 as &$data){
   $data['status'] = 1;
}
print_r($data1);

Output:-https://eval.in/975058

Reference:-

Passing by Reference

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

Comments

2

It's not exactly clear what you're trying to do but if you want to add the status flag to each of your items just try

foreach($data1 as &$item) {
   $item['status'] = 1;
}

This adds to every $item in $data1 the new associative key status with value 1

Comments

1

The "Passing by reference" solution above is probably the most elegant one but if you don't want to modify your existing array, you can do it like this:

foreach ( $data1 as $value )
{
    $value["status"] = 1;
    $data[] = $value;
}

var_dump ( $data );

Comments

1
<?php 
  foreach($data as $key=>$val){
      $data[$key]['status'] = 1;
  }
  echo "<pre>";
  print_r($data); 
?>

You can add status key in existing array.

1 Comment

Code-only answers are low-value on StackOverflow because they do very little to educate. Please edit your answer with the intent to educate the OP and thousands of future researchers regarding how your answer works and why it is a good technique.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.