Reputation: 6193
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?
Upvotes: 0
Views: 111
Reputation: 2654
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;
Upvotes: 1
Reputation: 20830
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.
Upvotes: 1
Reputation: 439
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'];
Upvotes: 0