Viewed   165 times

I have a array, which comes from $_POST[] and can have other arrays in it as values, like:

array(
 'title' => 'Title',
 'data' => array(
             'hdr' => 'Header'
             'bdy' => 'Body'
           ),
  'foo' => array(1, 23, 65),
  ...
)

How can I sanitize all values of this big array? for eg. apply a strip_tags() to values like Title, Header, Body, 1, 23, 65 etc ?

 Answers

1

Have a look at array_map

<?php  
$a = array(
'title' => 'Title',
'data' => array(
    'hdr' => 'Header',
    'bdy' => 'Body'
    ),
'foo' => array(1, 23, 65)
);

$b = array_map("strip_tags", $a);
print_r($b);
?>

Update for 2D array:

function array_map_r( $func, $arr )
{
    $newArr = array();

    foreach( $arr as $key => $value )
    {
        $newArr[ $key ] = ( is_array( $value ) ? array_map_r( $func, $value ) : ( is_array($func) ? call_user_func_array($func, $value) : $func( $value ) ) );
    }

    return $newArr;
}

Usage:

$a = array(
'title' => 'Title',
'data' => array(
    'hdr' => 'Header',
    'bdy' => 'Body'
    ),
'foo' => array(1, 23, 65)
); 

$ar =array_map_r('strip_tags', $a);
print_r($ar);

Note I found this just by searching the comments for Dimension

Thursday, October 13, 2022
2

My previous method was incredibly inefficient. I didn't realize how much data you were processing, but if we are upwards of 4000 lines, then efficiency is vital (I think I my brain was stuck thinking about strtr() related processing based on your previous question(s)). This is my new/improved solution which I expect to leave my previous solution in the dust.

Code: (Demo)

$myVar="My sister alannis Is not That blonde, here is a good place. I know Ariane is not MY SISTER!";
echo "$myVarn";

$myWords=array(
    array("is","é"),
    array("on","no"),
    array("that","aquela"),
    array("sister","irmã"), 
    array("my","minha"),
    array("myth","mito"),
    array("he","ele"),
    array("good","bom"),
    array("ace","perito"),
    array("i","eu")  // notice I must be lowercase
);
$translations=array_combine(array_column($myWords,0),array_column($myWords,1));  // or skip this step and just declare $myWords as key-value pairs

// length sorting is not necessary
// preg_quote() and QE are not used because dealing with words only (no danger of misinterpretation by regex)

$pattern='/b(?>'.implode('|',array_keys($translations)).')b/i';  // atomic group is slightly faster (no backtracking)
/* echo $pattern;
   makes: /b(?>is|on|that|sister|my|myth|he|good|ace)b/i
   demo: https://regex101.com/r/DXTtDf/1
*/
$translated=preg_replace_callback(
    $pattern,
    function($m)use($translations){  // bring $translations (lookup) array to function
        $encoding='UTF-8';  // default setting
        $key=mb_strtolower($m[0],$encoding);  // standardize keys' case for lookup accessibility
        if(ctype_lower($m[0])){ // treat as all lower
            return $translations[$m[0]];
        }elseif(mb_strlen($m[0],$encoding)>1 && ctype_upper($m[0])){  // treat as all uppercase
            return mb_strtoupper($translations[$key],$encoding);
        }else{  // treat as only first character uppercase
            return mb_strtoupper(mb_substr($translations[$key],0,1,$encoding),$encoding)  // uppercase first
                  .mb_substr($translations[$key],1,mb_strlen($translations[$key],$encoding)-1,$encoding);  // append remaining lowercase
        }
    },
    $myVar);

echo $translated;

Output:

My sister alannis Is not That blonde, here is a good place. I know Ariane is not MY SISTER!
Minha irmã alannis É not Aquela blonde, here é a bom place. Eu know Ariane é not MINHA IRMÃ!

This method:

  • does only 1 pass through $myVar, not 1 pass for every subarray of $myWords.
  • does not bother with sorting the lookup array ($myWords/$translations).
  • does not bother with regex escaping (preg_quote()) or making pattern components literal (Q..E) because only words are being translated.
  • uses word boundaries so that only complete word matches are replaced.
  • uses an atomic group as a micro-optimization which maintains accuracy while denying backtracking.
  • declares an $encoding value for stability / maintainability / re-usability.
  • matches with case-insensitivity but replaces with case-sensitivity ...if the English match is:
    1. All lowercase, so is the replacement
    2. All uppercase (and larger than a single character), so is the replacement
    3. Capitalized (only first character of multi-character string), so is the replacement
Monday, December 26, 2022
 
4

You need to iterate over your results, adding a new entry to the output when you encounter a new team, or updating the points value when you find the same team again. This is most easily done by initially indexing the output by the team name, and then using array_values to re-index the array numerically:

$teams = array();
foreach ($results as $result) {
    $team = $result['team'];
    if (!isset($teams[$team])) {
        $teams[$team] = array('team' => $team, 'points' => $result['punti']);
    }
    else {
        $teams[$team]['points'] += $result['punti'];
    }
}
$teams = array_values($teams);
print_r($teams);

Output (for your sample data):

Array
(
    [0] => Array
        (
            [team] => Red Bull Racing
            [points] => 418
        )
    [1] => Array
        (
            [team] => Scuderia Ferrari
            [points] => 353
        )
    [2] => Array
        (
            [team] => Mercedes-AMG
            [points] => 516
        )
    [3] => Array
        (
            [team] => Racing Point F1
            [points] => 147
        )
    [4] => Array
        (
            [team] => Haas F1
            [points] => 127
        )
)

Demo on 3v4l.org

Friday, August 12, 2022
 
4

A simple solution that comes to mind: combine array_filter and strpos;

$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');

$result = array_filter($strings, function($item) use($substrings) {
  foreach($substrings as $substring)
    if(strpos($item, $substring) !== FALSE) return TRUE;
  return FALSE;
});

To reset indices, you can use the array_values function.

Saturday, October 29, 2022
 
3

You can do it like this, do the calculation from the innermost of the array. Check the demo.

<?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);

Note:

traverse array from outer to inner
traverse array from inner to outer

Monday, November 14, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :