开发者

Adding Data to multidemensional array after or before foreach()

开发者 https://www.devze.com 2023-02-23 12:06 出处:网络
ich have thios foreach loop to开发者_开发问答 create an array. After or before it is created by the foreach, I want to add some values manually.

ich have thios foreach loop to开发者_开发问答 create an array. After or before it is created by the foreach, I want to add some values manually. I tried it in this way:

                $data = array();
            foreach ($xyz as $single):
                    $data[$dynamic_name] = $single->xyz;
            endforeach;
            $data[oid] = '####';

but in this way, only the last added values (oid) are stored in the rray. The rest gets deleted. Where ist the error in my code?


The error is you are overwriting $dynamic_name on each pass of the loop. Also you have two arrays in the example code. I think you may want something like:

$data = array();
foreach($xyz as $single)
{
    $data[] = $single->xyz;
}
$data['oid'] = '####'
print_r($data);

If this is not what you meant, please post more details.


You're code isn't correct PHP and I have trouble reading your question. I have the idea that you want to add entries to an array at multiple moments in your code.

<?php
$data = array();
$data[] = "First item before foreach";

$xyz = array();
$xyz[] = "1";
$xyz[] = "2";
$xyz[] = "3";

foreach ($xyz as $single) {
    $data[] = $single;
}

$data[] = "Last item after foreach";

var_dump($data);
?>

array(5) {
[0]=>
string(25) "First item before foreach"
[1]=>
string(1) "1"
[2]=>
string(1) "2"
[3]=>
string(1) "3"
[4]=>
string(23) "Last item after foreach"
}

Have a look at the PHP site for more information about this topic. http://php.net/manual/en/language.types.array.php

0

精彩评论

暂无评论...
验证码 换一张
取 消