Use foreach() to loop through object and change values
I've got a problem looping trough an object ( stdObject ) and altering a value.
What happens is:
- a query result comes in the function.
- It fetches the object to an 'array'
- After that I need to decode the content inside the object with html开发者_JS百科_entity_decode() to convert
&
etc. to readable characters...
Thats what is going wrong. I don't know how to put the converted string back into the object.
Here is the code of this function.
function jsonRequestHandlerUTF8($query) { $id = "0"; $message = errorHandler($id); $a_result = array(); if (mysql_num_rows($query) == 0) { //Empty sql query $id = '1'; $a_result = jSONErrorObject($id); } else { //No error occurred $a_result['ExceptionId'] = $id; $a_result['ExceptionMessage'] = $message; $a_result['Items'] = null; while ($my_result = mysql_fetch_object($query)) { $a_result['Items'][] = $my_result; } $test = $a_result['Items']; foreach ($test as $v1) { foreach ($v1 as $v2) { $v2 = html_entity_decode($v2, ENT_QUOTES, "utf-8") . "\n"; // Here should be code to get the $v2 inside the object again..... } } } $a_result = json_encode($a_result); return $a_result; }
$a_result['Items'] looks like this:
Array ( [0] => stdClass Object ( [idziekmeldingen] => 1 [meldingID] => 13190 [title] => Ziekmelding: Alex [published] => 2011-05-09 [updated] => 2011-05-09 [content] => Per 9-05-2011 heeft Alex zich ziek gemeld. [location] => AP [institute] => CMI [lastCron] => 2011-05-11 11:32:54 ) [1] => stdClass Object ( [idziekmeldingen] => 2 [meldingID] => 12933 [title] => Ziekmelding: Rimmert [published] => 2011-04-26 [updated] => 2011-04-26 [content] => Per 26-04-2011 heeft Rimmer zich ziek gemeld.Met vriendelijke groet,Luciënne [location] => AP [institute] => CMI [lastCron] => 2011-05-11 11:32:54 ) )
Use the &
symbol to pass the variables into the loop by-reference. This will mean you're modifying the actual variable rather than a copy of it.
foreach ($test as &$v1) {
foreach ($v1 as &$v2) {
$v2 = html_entity_decode($v2, ENT_QUOTES, "utf-8") . "\n";
}
}
(note, this only works in PHP 5.0 and up.... but if you're still using PHP4, you really need to upgrade!)
From the docs:
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.
Use references and assign into the current value.
You also can use these two ways for the same result.
Solution 1:
foreach($myobject as $k1 => &$v1) {
if($condition == true) {
$v1 = $newvalue;
}
}
Solution 2:
foreach($myobject as $k1 => $v1) { // here, no matter $v1 or &$v1
if ($condition == true) {
$myobject->{$k1} = $newvalue;
}
}
try this:
foreach($test as &$v){
foreach($v as &$v2)
// change value here ($v=....)
}
PHP References
精彩评论