php function sometimes pushing arrays other times objects - php

I have an app which i'm making a HTTP request via PHP to retrieve some XML data. I'm then taking a string in that data, splitting it by spaces (" ") and pushing it into a new array. I'm then taking an existing array and de-duping it against this new array using the function array_diff. Here is my code below:
// 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);
My issue is that in the resulting $mappedWordsObj array, I expect all the array items to be arrays themselves that contain the words but some of the items are getting inserted in the $mappedWordsObj as arrays with the words and others as objects with properties whos values are the words. Here is a snippet of the data returned:
{"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"],
I'd like to just have an array of arrays so can anyone please tell me where i've gone wrong?
Cheers

When you use json_encode, it will convert PHP arrays to either JSON arrays or JSON objects. Which one is output depends completely on the array keys in the PHP array. For PHP arrays with sequential, numeric indexes starting at 0, the JSON output will be an array. For PHP arrays with any other indexes, the JSON output will be an object.
The array_diff produces an array where the indexes are not sequential in some cases. You can use array_values to reindex the result before appending it to your output array.
array_push($mappedWordsObj, array_values($arr_1));
Side note - array_push actually isn't necessary here. You can use
$mappedWordsObj[] = array_values($arr_1);
The array_push documentation actually recommends doing it this way when you're only appending one item to the array. But, it's a pretty small optimization, so if array_push looks better to you, never mind. :)

Related

How do you find most common array in multidimensional array using PHP

I need to find the most common (most occurring) array in a multidimensional array. Not the most common values like this post - Find Common most values in multidimensional array in PHP - but rather the most common combination.
For example, if I have the following:
$a1=array(
array('704322062'),
array('678073776', '704322062'),
array('678073776', '704322062'),
array('704322064'),
array('704322062'),
array('678073776'),
array('678073776', '704322062')
);
I want to be able to detect that the array that occurs most often is array('678073776', '704322062') not that the string '704322062' is most common.
I've tried using array_intersect but couldn't get it working for this scenario.
Thanks!
array_count_values only works with scalar values, not when the items are arrays themselves. But we can still use that function, if we transform your arrays into strings first - by encoding them as JSON.
// fill temp array with items encoded as JSON
$temp = [];
foreach($a1 as $item) {
$temp[] = json_encode($item);
}
// count how many times each of those values occurs
$value_counts = array_count_values($temp);
// sort by number of occurrence, while preserving the keys
ksort($value_counts);
// pick the first key from the temp array
$first = array_key_first($value_counts);
This will get you ["678073776","704322062"] in $first now - you can json_decode it again, if you want your “original” array.
Note that this does not take into account, that two arrays could occur the same amount of times - then it will just pick the “random” first one of those. If you need to handle that case as well somehow, then you can determine the maximum value in $temp first, and then filter it by that value, so that only those keys of the corresponding arrays will be left.

Add " and create own json array in php

I my php file, I need to make my own Json array.
for($i=1;$i<$arraySize+1;$i++){
$idJson[$i]=$i.":".$birdIDArray[$i-1];
}
for($i=$arraySize+1 ;$i<$arraySize*2+1; $i++){
$idJson[$i]=$i.":".$rankArray[$i-($arraySize+1)];
}
When I use
print(json_encode($idJson));
the OUTPUT : ["0:3","1:15","2:3","3:14","4:1","5:2","6:2"]
But i need the output like this ["0":"3","1":"15","2":"3","3":"14","4":"1","5":2","6":"2"]
When I going to add " mark
for($i=1;$i<$arraySize+1;$i++){
$idJson[$i]=$i.'"'.":".'"'.$birdIDArray[$i-1];
}
for($i=$arraySize+1 ;$i<$arraySize*2+1; $i++){
$idJson[$i]=$i.'"'.":".'"'.$rankArray[$i-($arraySize+1)];
}
It prints like this
["0:3","1\":\"15","2\":\"3","3\":\"14","4\":\"1","5\":\"2","6\":\"2"]
How can I avoid from printing this \ sign?
I'm assuming you want a JSON object like this:
{"0":"3", ... }
The problem here is that Javascript/JSON distinguishes between key-value pairs, which are objects, and numerically indexed lists, which are arrays, while PHP uses arrays for both these things. With json_encode it depends on whether the PHP array is a continuously numerically indexed array, in which case you get a JSON array, or anything else, in which case you get a JSON object.
What you want is to force a JSON object even for a continuously numerically indexed array. The first question here would be: why?! But if you're really sure you want that (again, why?!), there's the JSON_FORCE_OBJECT flag in PHP 5.3+:
echo json_encode(array("3", "15", "3"), JSON_FORCE_OBJECT);
// {"0":"3","1":"15","2":"3"}
But I'll say again that that's pretty pointless. If you use a regular array like ["3","15","3"], the keys to those elements are already implicitly 0, 1 and 2. There's no need to enforce them as object keys.

Can't flatten multidimensional array with lots of duplicates

I'm trying to create a script that, based on an input a?? creates an array of all the combinations and permutations of all words containing an a and two other characters from the alphabet.
Values are such as a, ab, ba, dab, bga etc - as you may see the array contains (or should contain) a weird amount of values.
The problem is that the functions I use in the script outputs even more values with many duplicates.
And for some reason I can not create a flattened array without duplicates. I tried to use array_unique() but it doesn't work here. I tried to use explode() and implode() to flatten the result array, but no success. Even if I succeed to create a string from the values, when I try to transform this string into an array, the result is again the actual multi-dimensional array.
This drives me crazy, and as you see the code, I'm a beginner in PHP.
Any help to transform the actual multidimensional array to a flattened one without duplicates is highly appreciated. An example: actually the array contains 12168 sub-arrays, and only the string a occurs 1456 times. What I need is an array that doesn't have sub-arrays and contains each results only one time.
The PHP code is available at here
and the output is here:
Have you tried something like:
$inputString = 'a??';
$array = array();
if (strpos($inputString, 'a') !== false && !in_array($inputString, $array)) {
$array[] = $inputString;
}
echo '<pre>'; print_r($array); echo '</pre>';

JSON_ENCODE of multidimensional array giving different results

When doing a json_encode a multidimensional array in PHP, I'm noticing a different output simply by naming one of the arrays, as opposed to not naming them. For Example:
$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));
json_encode($arrytest)
gives a single array of multiple json objects
[{"a":1,"b":2},{"c":3},{"d":4}];
whereas simply assigning a name to the middle array
$arrytest = array(array('a'=>1, 'b'=>2),"secondarray"=>array('c'=>3),array('d'=>4));
json_encode($arrytest)
creates a single json object with multiple json objects inside
{"0":{"a":1,"b":2},"secondarray":{"c":3},"1":{"d":4}};
why would the 1st option not return the same reasults as the 2nd execpt with "1" in place of "secondarray"
In JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d.
If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON.
$arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));
// Force the outer structure into an object rather than array
echo json_encode($arrytest , JSON_FORCE_OBJECT);
// {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}}
Arrays with continuous numerical keys are encoded as JSON arrays. That's just how it is. Why? Because it makes sense.
Since the keys can be expressed implicitly through the array encoding, there is no reason to explicitly encoded them as object keys.
See all the examples in the json_encode documentation.
At the first option you only have numeric indexes (0, 1 and 2). Although they are not explicitly declared, php automatically creates them.
At the second option, you declare one of the indexes as an string and this makes PHP internally transform all indexes to string.
When you json encode the first array, it's not necessary to show the integers in the generated json string because any decoder should be able to "guess" that they are 0, 1 and 2.
But in the second array, this is necessary, as the decoder must know the key value in your array.
It's pretty simple. No indexes declared in array? Them they are 0, 1, 2, 3 and so on.
output of this as in json form is year1{a,b},year2{c}, year3{d}
**a has value 1 ,b=2,c=3,d=4 stored in array of year1's a,b years2's c and years3's d respectivily
$array1 = array('a'=>1, 'b'=>2);
$array2 = array('c'=>3);
$array3 = array('d'=>4)
$form = array("year1" =>$array1,
"year2" =>$array2,
"year3" =>$array3,
);
$data = json_encode($form);

Get arbitrary number of random elements from a php array in one line

I wanted to pull an arbitrary number of random elements from an array in php. I see that the array_rand() function pulls an arbitrary number of random keys from an array. All the examples I found online showed then using a key reference to get the actual values from the array, e.g.
$random_elements = array();
$random_keys = array_rand($source_array);
foreach ( $random_keys as $random_key ) {
$random_elements[] = $source_array[$random_key];
}
That seemed cumbersome to me; I was thinking I could do it more concisely. I would need either a function that plain-out returned random elements, instead of keys, or one that could convert keys to elements, so I could do something like this:
$random_elements = keys_to_elements(array_rand($source_array, $number, $source_array));
But I didn't find any such function(s) in the manual nor in googling. Am I overlooking the obvious?
What about usung array_flip? Just came to my mind:
$random_elements = array_rand(array_flip($source_array), 3);
First we flip the array making its values become keys, and then use array_rand.
An alternate solution would be to shuffle the array and return a slice from the start of it.
Or, if you don't want to alter the array, you could do:
array_intersect_key($source_array, array_combine(
array_rand($source_array, $number), range(1, $number)));
This is a bit hacky because array_intersect can work on keys or values, but not selecting keys from one array that match values in another. So, I need to use array_combine to turn those values into keys of another array.
You could do something like this, not tested!!!
array_walk(array_rand($array, 2), create_function('&$value,$key',
'$value = '.$array[$value].';'));

Categories