0

I need to add some details to an array without overwriting the old data.

At the moment I have something like this if I print_r($data)

 Array
 (
   [one] => Hello
   [two] => Hello World
 )

I then have a function that adds some data to the array

 foreach ($rubric as $rs){
      if($rs['position']==1){$data['one']=$rs;}
  if($rs['position']==2){$data['two']=$rs;}
 }

This gives me the following if I print_r($data)

Array
(
   [one] => Array
      (
         [id] => 1
      )
   [two] => Array
      (
         [id] => 2
      )
)

Does anyone have any ideas

What I would like to do is....

 foreach ($rubric as $rs){
      if($rs['position']==1){$data['one']['details']=$rs;}
  if($rs['position']==2){$data['two']['details']=$rs;}
 }

With the aim of adding a new subarray called "details" within each array item...

Does that make sense? If I try to run that code however I get the following error

A PHP Error was encountered Severity: Notice Message: Array to string conversion

Could someone tell me what I'm doing wrong?

2
  • 1
    what would be the desired result? Commented Aug 21, 2012 at 17:23
  • I find this question to be unclear. I don't see a clear minimal reproducible example. Commented Jun 25, 2024 at 10:36

3 Answers 3

1

See, array_push array_unshift.

Array push puts an element at the end. Array unshift adds a number to the beginning of the array.

You can also use the structure

$myArray['nameOfNewElement']=$newElement;

This adds $newElement to the array $myArray;

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

2 Comments

Thats what I'm trying to do... that would be prefect but when I try to do that I get "A PHP Error was encountered Severity: Notice Message: Array to string conversion" Any ideas?
The previous syntax I put in was a little more advanced, so I changed it. What's in there now should work.
1

You can use array_merge.

According to your question, here is the solution :

// sample array
$rubric = array(0=> array("position"=>1),1 => array("position"=>2));
$data = array("one" => "Hello","two" => "hello world");
foreach ($rubric as $rs){
      if($rs['position']==1){
           $d= array_merge($data,$rs);
      }
      if($rs['position']==2){
          $d= array_merge($data,$rs);
      }
 }
print_r($d);

Here is the working DEMO : http://codepad.org/rgKiv542

Hope, it'll help you.

Comments

0

When you write $data['one'] = $rs;, you are assigning $rs to overwrite the value "Hello".

Perhaps what you were trying to do is

$data['three'] = $rs['id'];

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.