简体   繁体   中英

PHP - get unique strings from array

I am new to this place and I have a question about PHP that I can't figure out.

What I am trying to do is create an array of strings, but that's not the problem. The problem is I have no idea how to get the only string that I need.

Example code:

$array = [];
$array[$game] = $string;

I want to keep creating strings for one single game but there will but more and more strings coming in the array from different games. I want to get only the ones from a single game, I don't know if you get what I'm talking about but I hope so because I'm frustrated that I can't figure out a way.

You have to create sub array for each game then set strings inside

// checking it sub array already not exits to not overwrite it
if( isset($array[$game]) ){ 
    $array[$game] = array();
}

then only insert your string inside it

$array[$game][] = $string1; 
$array[$game][] = $string2;
...

as result you will have

array('somegame' => array(
                         0 => "some game string 1",
                         1 => "some game string 2",
                         ...
                    )
)

Your question is too simple.

You are already appending the strings to array by the key of game id.

$array = [];
$array[$game] = $string;

So, your array will look like:

array(
  1 => array('string 1', 'string 2'),
  2 => array('string 3', 'string 4'),
  3 => array('string 5', 'string 6'),
  //..... and more
)

Where keys 1, 2 and 3 are the game ids.

If you want to retrieve the keys in case of game ids 1 and 2:

$game = 1;
$gameStringsOne = $arr[$game];

$game = 2;
$gameStringsTwo = $arr[$game];

Use multi-dimensional array like

$array = [];
$array[$game] = [ $string1, $string2 ];

Read the docs Use a multi-dimentional array, push strings to an array and then assign that to another array, that way you can have multiple strings to a game

<?php
    $stringArray = array("str","str2");
    // if needed do array_push($stringArray,"str3","str4");
    array_push($gamelist['game'], $stringArray);
?>

get an array of strings when acessing game from gamelist

read more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM