PHP包含另一个文件,循环数组和每个记录的运行函数

I would like to access the values of an array in another php file ... loop over it and run a function over each record. I can't seem to access the values though ... I'm getting an internal error. How to properly do this? That's my setup:

contacts.php

<?php

$contacts_de = array(
    'name01' => array(
        'firstName' => 'FirstName01',
        'lastName' => 'LastName01',
        'gender' => 'm',
        'language' => 'de',
        'email' => 'email01'
    ),
    'name02' => array(
        'firstName' => 'FirstName02',
        'lastName' => 'LastName02',
        'gender' => 'f',
        'language' => 'de',
        'email' => 'email02'
    )
);

mail.php

<?php

include('contacts.php');

function renderContacts($arr) {
    global $lang,$contacts_de;
    $d = '';
    foreach($arr as $i) {
        if ($i['gender'] == 'm') {
            .$d = 'Mr. '.$i['firstName'].' '.$i['lastName']
        } else if ($i['gender'] == 'm') {
            .$d = 'Ms. '.$i['firstName'].' '.$i['lastName']
        }
    }
    echo $d;
}

renderContacts();

default.js

$('#sendbtn').on('click', function() {

    $.ajax({
        type: "POST",url: '/mail.php',
        success: function(response,textStatus,jqXHR) {
            console.log(response);

        },
        error: function (jqXHR, status, err) {
            console.log(err);
        }
    });

}); 

Desired Console.log

Mr. FirstName01 LastName01
Ms. FirstName02 LastName02

The simple answer to what you're asking is:

<?php # contacts.php

$contacts = array(
    'name01' => array(
        'firstName' => 'FirstName01',
        'lastName' => 'LastName01',
        'gender' => 'm',
        'language' => 'de',
        'email' => 'email01'
    ),
    'name02' => array(
        'firstName' => 'FirstName02',
        'lastName' => 'LastName02',
        'gender' => 'f',
        'language' => 'de',
        'email' => 'email02'
    )
);

and

<?php # whatever.php

require __DIR__ . '/contacts.php';

function render_contacts(array $contacts) {
    foreach ($contacts as $contact) {
        $prefix = $contact['gender'] == 'm' ? 'Mr' : 'Ms';
        printf("%s. %s %s
", $prefix, $contact['firstName'], $contact['lastName']);
    }
}

render_contacts($contacts);

A non-separated sandbox can be seen here: http://sandbox.onlinephpfunctions.com/code/6daa0147671fcaac9c51fe919c4a8f916181fad1

I've also cleaned up your code a little bit for you, removing things like the global keyword, some syntax errors, and the JavaScript you linked, as it's irrelevant to the issue.

GL.