문제

I have array of stdClass :

array (size=2)
  0 => 
    object(stdClass)[2136]
      public 'id' => string '1946' (length=4)
      public 'office' => string 'test' (length=4)
      public 'level1' => string 'test level 1' (length=12)

  1 => 
    object(stdClass)[2135]
      public 'id' => string '1941' (length=4)
      public 'office' => string 'test' (length=4)

How can i wrap every 'test' value with span tag ?

도움이 되었습니까?

해결책

foreach ($array as $stdClass)
    foreach ($stdClass as &$value) // reference
        if ($value === "test")
            $value = "<span>".$value."</span>";

Simply iterate over the array and the class as they're both iterable with foreach. (Iterate over the class by reference, else it won't be changed)

다른 팁

To wrap all the object values which match the word 'test' in a span, you will need to iterate through the object properties as well as the array itself. You can do this using foreach:

foreach ($object in $array) {
    foreach ($property in $object) {
        if ($object->$property == 'test') {
            $object->$property = "<span>{$object->property}</span>";
        }
    }
}

If you want to wrap all instances of the word test within property values with a span, you can do it using preg_replace as follows:

foreach ($object in $array) {
    foreach ($property in $object) {
        $object->$property = preg_replace('/\b(test)\b/', '<span>$1</span>', $object->$property);
    }
}

Given the string "This test is for testing purposes as a test", the above call will spit out this:

This <span>test</span> is for testing purposes as a <span>test</span>.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top