Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 2 values to 1 key in a PHP array

Tags:

arrays

php

I have a result set of data that I want to write to an array in php. Here is my sample data:

**Name** **Abbrev**
Mike     M
Tom      T
Jim      J

Using that data, I want to create an array in php that is of the following:

1|Mike|M
2|Tom|T
3|Jim|j

I tried array_push($values, 'name', 'abbreviation') [pseudo code], which gave me the following:

1|Mike
2|M
3|Tom
4|T
5|Jim
6|J

I need to do a look up against this array to get the same key value, if I look up "Mike" or "M".

What is the best way to write my result set into an array as set above where name and abbreviation share the same key?

like image 648
Mike Munroe Avatar asked Jun 17 '10 21:06

Mike Munroe


People also ask

Does += work on arrays in PHP?

The + operator in PHP when applied to arrays does the job of array UNION. $arr += array $arr1; effectively finds the union of $arr and $arr1 and assigns the result to $arr .

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


2 Answers

maybe you create a simple class for that as the abbreviation is redundant information in your case

class Person
{
    public $name;

    pulbic function __construct($name)
    {
        $this->name = (string)$name;
    }

    public function getAbbrev()
    {
        return substr($this->name, 0, 1);
    }

    public function __get($prop)
    {
        if ($prop == 'abbrev') {

            return $this->getAbbrev();
        }
    }
}


$persons = array(
    new Person('Mike'),
    new Person('Tom'),
    new Person('Jim')
);

foreach ($persons as $person) {

   echo "$person->name ($person->abbrev.)<br/>";
}
like image 104
Andreas Linden Avatar answered Sep 19 '22 09:09

Andreas Linden


PHP's not my top language, but try these:

array_push($values, array("Mike", "M"))
array_push($values, array("Tom", "T"))
array_push($values, array("Jim", "J"))

$name1 = $values[1][0]
$abbrev1 = $values[1][1]

or:

array_push($values, array("name" => "Mike", "abbrev" => "M"))
array_push($values, array("name" => "Tom", "abbrev" => "T"))
array_push($values, array("name" => "Jim", "abbrev" => "J"))

$name1 = $values[1]["name"]
$abbrev1 = $values[1]["abbrev"]

The trick is to use a nested array to pair the names and abbreviations in each entry.

like image 44
Walter Mundt Avatar answered Sep 18 '22 09:09

Walter Mundt