0

Hello I am setting a key value pair in an array in a foreach loop

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"
 }

I am doing this via a foreach loop

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;

}

}

But the output is this

[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"
}

Rather than the example I gave at the start of the question. How can I get the array to fill in key values pairs like the first example.

4

3 回答 3

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'将新项目添加到数组中。如果您在那里添加一些第二维键,它不会改变。

于 2012-10-11T14:25:02.137 回答
0

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

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

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

于 2012-10-11T14:54:59.757 回答
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;
}

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

于 2012-10-11T14:34:18.457 回答