Question

I want have an array that is created from a database to populate a table

array (size=2)
  number of friends => 3
  friends details => array (size=3) 
    0 => 
        array (size=4)
          'bithday' => string '2000-02-04' (length=10)
          'email' => string 'someone@example.com' (length=11)
          'town' => string 'OXFORD' (length=6)
          'status' => string 'FRIENDS' (length=5)

    2 => 
        array (size=4)
          'bithday' => string '2000-02-04'(length=10)
          'email' => string 'someone@example.com' (length=11)
          'town' => string 'OXFORD' (length=6)
          'status' => string 'NOT FRIENDS' (length=9)
    3 => 
        array (size=4)
          'bithday' => string '2000-02-04'(length=10)
          'email' => string 'someone@example.com' (length=11)
          'town' => string 'CAMBRIDGE' (length=8)
          'status' => string 'FRIENDS' (length=5)

I have (unsuccessfully) being trying to do a str_replace on the email string if the correct conditions are met, so I want to be able to replace the email address of all my friends in oxford with a button that allows me to email them with one press

so someone@example.com becomes

      <button action=invitePal>Invite your pal!</button>

But I only want this to happen if the array says that they meet both criteria to change it, so if I am having a party in Oxford, the invite button only appears on the entries for 'friends' in Oxford.

Was it helpful?

Solution

A pretty standard method for this would be to loop though like so:

foreach($people as $index => $person) {

    if($person['status'] === 'FRIENDS' && $person['town'] === 'OXFORD') {

        // Change the original string, echo it out, or do whatever.
        // If you need the email in this string, you can reference it via:
        // $person['email']
        $people[$index]['email'] = '<button action=invitePal>Invite your pal!</button>';

    }

}

An alternative method would be to use array_map and an anonymous function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top