foreach
ループ内のオブジェクトのいくつかのプロパティを変更したいと思います:
foreach ($object->array as $element) {
$element['foo'] = $new_foo;
$element['bar'] = $new_bar;
}
関数でこれを行うにはどうすればよいですか?または、オブジェクト指向のアプローチでこれを行うにはどうすればよいですか? $handle
関数内の変数の値のみを変更するため、私のコードは機能しません。
function change_attribute(&$handle, $new_value) {
$handle = $new_value;
}
foreach ($object->array as $element) {
change_attribute($element['foo'], $new_foo);
change_attribute($element['bar'], $new_bar);
}
実際のコード
foreach ($xml->database[0]->table as $table) {
$table->column[1]['name'] = 'new value';
}
配列要素を参照せずにオブジェクトを正常に更新し$xml
ます (致命的なエラーが発生します)。この関数で同じことができないのはなぜですか?
function change_attribute(&$handle, $old, $new) {
if ($handle == $old) {
$handle = $new;
}
}
foreach ($xml->database[0]->table as $table) {
change_attribute($table->column[1]['name'], 'old value', 'new value');
}
$xml
オブジェクト_
php > var_dump($xml->database[0]->table);
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(1) {
["name"]=>
string(7) "objects"
}
["column"]=>
array(5) {
[0]=>
string(4)
[1]=>
string(1)
[2]=>
string(17)
[3]=>
string(17)
[4]=>
string(1949)
}
}
var_dump($xml->database[0]->table[0])
これは、後者が であることを除いて、と同じですobject(SimpleXMLElement)#4 (2)
。
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(1) {
["name"]=>
string(9) "old value"
}
[0]=>
string(1) "2"
}