質問

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