php explode - 将数组拆分成行

php explode - split array into rows

我有一个有 3 列的小部件 姓名 / 职业 / 注册 用户可以想加多少人就加多少。

但是数据是这样传来的:

数组 ( [0] => [{"Name":"Bob [1] => Smith","Occupation":"Administrator","Registration":"1234"},{ "Name":"James [2] => Richards","Occupation":"Technician","Registration":"4345353"}] )

PHP 使用代码:

$people=$_POST['q36_addIndividuals'];
$str = $people;
print_r (explode(' ',$str));

我想要的是它看起来像这样:

Bob Smith - 管理员 - 1234
詹姆斯·理查兹 - 技术员 - 4345353

print_r函数只是粘贴数组的结构。

如果你想要不同的形式,你需要遍历数组并为每个元素写出来:

 foreach($people as $element){
  echo $element['Name']." - ".
  $element['Occupation']." - ".
  $element['Registration'];  
 }

您只有一些 JSON 数据,但它不正确。

正确的版本应该是:

$data = '[{"Name":"Bob [1] => Smith","Occupation":"Administrator","Registration":"1234"},{"Name":"James [2] => Richards","Occupation":"Technician","Registration":"4345353"}]';

$data = json_decode($data);

foreach ($data as $json) {

    echo $json->Name . ' - ' . $json->Occupation . ' - ' . $json->Registration;
    echo "\n";
}

这将输出如下内容:

Bob [1] => Smith - Administrator - 1234  
James [2] => Richards - Technician - 4345353

但是您应该考虑将名字和姓氏存储在两个不同的值中,这样您就可以访问它们。

您也可以 "remove" [n] =>,但这是肮脏的方式。我不推荐这个!

$data = '[{"Name":"Bob [1] => Smith","Occupation":"Administrator","Registration":"1234"},{"Name":"James [2] => Richards","Occupation":"Technician","Registration":"4345353"}]';

$data = json_decode($data);

foreach ($data as $json) {

    $json->Name = preg_replace(['/[[(0-9)]]|[=>]|[[]|/', '/   /'], ['', ' '], $json->Name);
    echo $json->Name . ' - ' . $json->Occupation . ' - ' . $json->Registration; // not recommended
    echo "\n";
}