简体   繁体   English

PHP-无法为三维数组增加价值

[英]PHP - Trouble adding value to third dimensional array

I have a this array scenario at first: 首先我有一个这个数组场景:

$_SESSION['player_1_pawn'][] = 'Warrior';

now when I want to add a third dimensional value like this: 现在,当我想添加第三维尺寸时,如下所示:

$_SESSION['player_1_pawn'][0]['x'] = 1;

I get this output from 我从这个输出

>$_SESSION['player_1_pawn'][0] : '1arrior'

My question is that, how to make that value stays intact as Warrior instead of 1arrior ? 我的问题是,如何使这一价值作为“ Warrior而不是“ 1arrior

If the value is already a string, ['x'] accesses the first character of that string (yeah, don't ask ;)). 如果值已经是一个字符串,则['x']访问该字符串的第一个字符(是的,不要问;))。

If you want to replace the whole thing with an array, do: 如果要用数组替换整个对象,请执行以下操作:

$_SESSION['player_1_pawn'][0] = array('x' => 1);

You cannot have $_SESSION['player_1_pawn'][0] be both the string "Warrior" and an array at the same time, so figure out which you want it to be. $_SESSION['player_1_pawn'][0]不能同时是字符串“ Warrior” 一个数组,因此要弄清楚它是哪个。 Probably: 大概:

$_SESSION['player_1_pawn'][0] = array('type' => 'Warrior', 'x' => 1);

Your problem is that $_SESSION['player_1_pawn'][0] is a scalar value equal to "Warrior". 您的问题是$_SESSION['player_1_pawn'][0]是等于“ Warrior”的标量值。 When you treat a scalar as an array, like you do with $_SESSION['player_1_pawn'][0]['x'] which evalueates $_SESSION['player_1_pawn'][0][0] or "W", you just change the first character in the string. 当您将标量作为数组对待时,就像您使用$_SESSION['player_1_pawn'][0]['x']来评估$_SESSION['player_1_pawn'][0][0]或“ W”一样,更改字符串中的第一个字符。

If you want to keep "Warrior" try this: 如果您想保留“战士”,请尝试以下操作:

$_SESSION['player_1_pawn']=array('Warrior', 'x'=>1);

ETA: ETA:

given your requirements, the structure is this: 根据您的要求,结构如下:

$_SESSION['player_1_pawn'] = array(
  0 => array('Warrior', 'x'=>1),
  1 => array('Wizard', 'x'=>7), //...
);

Which means you add like this: 这意味着您可以这样添加:

$_SESSION['player_1_pawn'][]=array('Warrior', 'x'=>1);

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

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