简体   繁体   English

PHP-从数组获取唯一字符串

[英]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. 我是这个地方的新手,我有一个我无法解决的有关PHP的问题。

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. 您已经通过游戏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. 其中键1、2和3是游戏ID。

If you want to retrieve the keys in case of game ids 1 and 2: 如果要在游戏ID 1和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 gamelist时获取字符串数组

read more 阅读更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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