php函数有时会推送数组其他时候的对象

时间:2017-05-25 14:44:09

标签: php

我有一个应用程序,我通过PHP发出HTTP请求来检索一些XML数据。然后我在该数据中取一个字符串,用空格(array_diff)拆分并将其推入一个新数组。然后我使用函数 // THIS ARRAY IS MUCH LONGER BUT HAVE JUST PUT IN A FEW WORDS $stopwords = array("a", "about", "above", "above", "across", "after", "afterwards", "again"); // this is my XML call $test = simplexml_load_file('https://some-xml-endpoint.com/endpoint'); // defining a blank array where I want the result to go $mappedWordsObj = []; for($i = 0;$i < count($test->data);$i++) { // if I echo this it returns me a string with no quotes (sometimes the quotes would be in there and I thought this may have been the issue) $comment = chop(strtolower($test->data[$i]->comments)); // here I split the comment into an array by spaces $wordsArray = explode(' ', $comment); //here I compare my new array of words with the stopwords I want removed from the wordsArray $arr_1 = array_diff($wordsArray, $stopwords); // here I push into the $mappedWordsObj array array_push($mappedWordsObj, $arr_1); } // here I push to the DOM the result to see how my array looks echo json_encode($mappedWordsObj); 获取现有数组并使用函数对这个新数组进行重复数据删除。以下是我的代码:

$mappedWordsObj

我的问题是,在生成的$mappedWordsObj数组中,我希望所有数组项都是包含单词的数组本身,但是有些项目会作为数组插入到{"0":"i","1":"just","2":"want","4":"switch","6":"existing","7":"t-mobile","8":"pay","13":"ee","14":"pay","15":"monthly.","16":"i","17":"don't","18":"want","20":"new","21":"phone!","23":"page","24":"does","26":"tell","31":"this!"},{"0":"just","2":"option","4":"'sim","5":"only'","9":"'radio","10":"button'","11":"forced","12":"selection."}, ["voice","recignition"], ["testing","ol"], {"0":"can't","1":"think","4":"i","7":"simple","9":"easy"},{"2":"instead","3":"lol"}, ["n\/a"], ["great","website"], 中。单词和其他作为具有属性的对象,其值是单词。以下是返回数据的片段:

public int count8(int n) {
int a,b;
if(n==0)
return 0;
a=n%10;
b=(n/10)%10;
if(a==8&&b==8)
return 2+count8(n/10);
else if(a==8&&b!=8)
return 1+count8(n/10);
else
return count8(n/10);

我想拥有一系列数组,所以有人可以告诉我哪里出错了吗?

干杯

1 个答案:

答案 0 :(得分:1)

使用array_diff时,它会将PHP数组转换为JSON数组或JSON对象。输出哪一个完全取决于PHP数组中的数组键。对于具有从0开始的顺序数字索引的PHP数组,JSON输出将是一个数组。对于具有任何其他索引的PHP数组,JSON输出将是一个对象。

array_values生成一个数组,其中索引在某些情况下不是连续的。您可以使用array_push($mappedWordsObj, array_values($arr_1)); 重新索引结果,然后再将其附加到输出数组。

array_push

旁注 - $mappedWordsObj[] = array_values($arr_1); 实际上不是必需的。你可以使用

array_push

The array_push documentation实际上建议在您只将一个项目附加到数组时以这种方式执行此操作。但是,这是一个非常小的优化,所以如果{{1}}看起来更好,请不要介意。 :)