在foreach循环PHP中的数组中设置值

时间:2012-10-11 14:21:42

标签: php arrays loops foreach key-value

您好我在foreach循环中的数组中设置键值对

e.g

array(2) {
  [0]=>
  array(1) {
  ["resourceType"]=>
  string(4) "File"
  ["resourceName"]=>
  string(4) "Test"

  [1]=>
  array(1) {
  ["resourceType"]=>
  string(4) "File"
  ["resourceName"]=>
  string(4) "Test"
 }

我是通过foreach循环来做到这一点

foreach ($output as $data) {



$resourceType = strpos($data, "d");

if ($resourceType) {

    $ftpArray[]['resourceType'] = "Folder";
} else {

    $ftpArray[]['resourceType'] = "File";
}

$resourceName = strrchr($data, " ");

$resourceName = trim($resourceName);

if ($resourceName != ".." && $resourceName != "." && $resourceName != "") {

    $ftpArray[]['resourceName'] = $resourceName;

}

}

但输出是这个

[0]=>
array(1) {
["resourceType"]=>
string(4) "File"
}
[1]=>
array(1) {
["resourceType"]=>
string(4) "Test"
}
[2]=>
array(1) {
["resourceType"]=>
string(4) "File"
}
[3]=>
array(1) {
["resourceName"]=>
string(9) ".htaccess"
}

而不是我在问题开头给出的例子。如何让数组填充键值对,如第一个例子。

3 个答案:

答案 0 :(得分:1)

制作一个tmp数组

foreach ($output as $data) { 
  $a = array();
  if (strpos($data, "d")) { 
    $a['resourceType'] = "Folder"; 
  } else { 
    $a['resourceType'] = "File"; 
  } 
  $resourceName = trim(strrchr($data, " ")); 
  if ($resourceName != ".." && $resourceName != "." && $resourceName != "") { 
    $a['resourceName'] = $resourceName; 
  } 
  $ftpArray[] = $a; 
} 

每次调用$ftpArray[] = 'x'都会向数组中添加新项。如果你添加一些第二维键,它就不会满足。

答案 1 :(得分:0)

您想要将数据结构添加到数组中。这样,创建数据结构,做你的东西并将它添加到数组中:

foreach ($output as $data) {
  $struct = array('resourceType' = > '', 'resourceName' => '');

  // do stuff, on the struct

  $resourceType = strpos($data, "d");
  if ($resourceType) {
    $struct['resourceType'] = "Folder";
  } else {
    $struct['resourceType'] = "File";
  }

  $resourceName = strrchr($data, " ");
  $resourceName = trim($resourceName);

  if ($resourceName != ".." && $resourceName != "." && $resourceName != "") {
    $struct['resourceName'] = $resourceName;
 }
 $ftpArray[] = $struct;
}

请注意,与前一个答案存在子图块差异,因为始终会创建结构。

答案 2 :(得分:0)

数组上的每个[]操作都会向循环添加一个新元素,因此您需要创建一个临时值,然后将其添加到循环中:

$element = array();
// set the data here
$output_array[] = $element

第二件事,那个脚本字符串的位置从0开始,所以如果你需要知道在使用strpos时找不到该字符,你应该用===或!==检查返回值是否为FALSE。