php foreach with multidimensional array

后端 未结 12 1672
一向
一向 2020-11-27 05:10

I\'m developing a php app that uses a database class to query mySQL.

the class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/

12条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 05:17

    If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.

    In this usage, I have this array with each element needing an appended comma and newline.

    $some_array = [];
    

    data in $some_array
    0: "Some string in an array"
    1: "Another string in an array"

    Per php.net

    If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

    array_walk_recursive($some_array, function (&$value, $key) {
        $value .= ",\n";
    });
    

    Result:
    "Some string in an array,\n"
    "Another string in an array,\n"

    Here's the same concept using array_walk to prepend the database table name to the field.

    $fields = [];
    

    data in $fields:
    0: "FirstName"
    1: "LastName"

    $tbl = "Employees"
    
    array_walk($fields, 'prefixOnArray', $tbl.".");
    
    function prefixOnArray(&$value, $key, $prefix) { 
        $value = $prefix.$value; 
    }
    

    Result:
    "Employees.FirstName"
    "Employees.LastName"


    I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.

提交回复
热议问题