John Davidson

PHP: Loop through multidimensional array and remove html tags

0 comments
Message:


I want to loop through an multidimensional array, which has multiple keys and arrays of strings assigned to the keys. For each string in the arrays, I want to execute the strip_tags function and replace the old string with the new one.


I am very new to php and I am very confused.


So thanks for your help!


EDIT:


This is what I did so far:


<?php
include ('../db.php');


$sql = "select id, post_title, post_content, post_type, post_date from wp_posts where post_type = 'post' order by post_date desc limit 20";
$ergebnis = $db->query($sql);

$zeile = $ergebnis->fetchALL(PDO::FETCH_ASSOC);

$keys = array_keys($zeile);

$valuearray = array();


for($i=0; $i < count($keys); $i++) {

foreach($zeile[$keys[$i]] as $key => $value) {
if(is_string($value) == true) {
$value1 = strip_tags($value);
array_push($valuearray, $value1);
$zeile[$keys[$i]] = $valuearray;
}
else {
array_push($valuearray, $value);
$zeile[$keys[$i]] = $valuearray;
}
}
}



$json = json_encode($zeile);

echo $json;

?>


I need the output as json for flutter development.



My Answer:
Here is an example of how you can loop through a multidimensional array and remove HTML tags from the strings:

php

// Sample multidimensional array
$data = array(
'key1' => array('string1', '

string2

'),
'key2' => array('
string3
', 'string4')
);

// Loop through the array
foreach ($data as $key => $value) {
foreach ($value as $index => $string) {
// Remove HTML tags from the string
$data[$key][$index] = strip_tags($string);
}
}

// Output the updated array
print_r($data);

?>


In this example, we have a multidimensional array `$data` with keys and arrays of strings assigned to the keys. We use nested foreach loops to iterate through each string in the arrays and apply the `strip_tags` function to remove HTML tags. The updated strings are then stored back in the original array.

You can run this code in a PHP file or online PHP editor to see the updated array without HTML tags. Let me know if you need any further clarification or assistance.

Rate this post

3 of 5 based on 4147 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us