【发布时间】:2017-06-15 08:46:05
【问题描述】:
我正在尝试使用我正在切割的字符串数组在 PHP 中构建一个多维数组,因此 1:wlrb@yahoo.com:7:8.35 的字符串变为
"id": "1",
"email_address": "wlrb@yahoo.com",
"domain": "yahoo.com",
"number_of_orders": "7",
"total_order_value": "£8.35"
在 JavaScript 中,我会创建一个包含上述值的对象并将其放入数组中,但 PHP 中的等价物是什么? 到目前为止,我有下面的代码,它给了我
Array ( [0] => stdClass Object ( [id] => 1 [email] => wlrb@yahoo.com [domain] => yahoo.com [number_of_orders] => 7 [total_order_value] => 8.35)
<?php
$data = file_get_contents('orderdata');
/* echo $data; */
$lines = explode("\n", $data);
array_splice($lines, 0, 8);
/* var_dump($lines); */
array_splice($lines, -3);
/* var_dump($lines); */
/* removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values */
$lines = array_values(array_filter($lines, 'strlen'));
function arraySort($lines ,$i) {
$rep = new stdClass();
$rep->id = strId($lines, $i);
$rep->email = strEmail($lines, $i);
$rep->domain = strDomain($lines, $i);
$rep->number_of_orders = orderNo($lines, $i);
$rep->total_order_value = orderValue($lines, $i);
/* var_dump($rep); */
return $rep;
}
function strDomain($lines, $i) {
if($lines[$i] == null){
return "";
}
else {
$str = $lines[$i];
$splt = explode(':', $str);
$domain = explode('@', $splt[1]);
return $domain[1];
}
}
function strId($lines, $i) {
if($lines[$i] == null){
return "";
}
else {
$str = $lines[$i];
$splt = explode(':', $str);
return $splt[0];
}
}
function strEmail($lines, $i) {
if($lines[$i] == null){
return "";
}
else {
$str = $lines[$i];
$splt = explode(':', $str);
return $splt[1];
}
}
function orderNo($lines, $i) {
if($lines[$i] == null){
return "";
}
else {
$str = $lines[$i];
$splt = explode(':', $str);
return $splt[2];
}
}
function orderValue($lines, $i) {
if($lines[$i] == null){
return "";
}
else {
$str = $lines[$i];
$splt = explode(':', $str);
return '£' + $splt[3];
}
}
$reports = array();
$reps = array();
for($i = 0, $length = count($lines); $i < $length; ++$i) {
$reps = arraySort($lines, $i);
array_push($reports, $reps);
}
?>
但是当我尝试用
搜索数组时$filteredArray =
array_filter($reports, function($element) use($search){
return isset($element['domain']) && $element['domain'] == $search;
});
我收到以下错误
致命错误:未捕获的错误:无法将 stdClass 类型的对象用作 phpData.php 中的数组:110 堆栈跟踪:#0 [内部函数]: {closure}(Object(stdClass)) #1 phpData.php(111): array_filter(数组, Object(Closure)) #2 {main} 抛出 第 110 行的 phpData.php
这是因为在我的 arraySort 函数中使用了$rep = new stdClass();吗?如果是这样,我应该使用什么?
【问题讨论】:
-
是的,这就是原因,您尝试将对象用作数组,只有将对象传递给
\ArrayObject(php.net/manual/en/class.arrayobject.php) 或仅使用数组时才有可能跨度>
标签: php arrays multidimensional-array