This question already has answers here:
How to reindex an array?
(6 answers)
Closed 1 year ago.
I've encoded an Array I've made using the inbuilt json_encode(); function. I need it in the format of an Array of Arrays like so:
[["Afghanistan",32,12],["Albania",32,12]]
However, it is returning as:
{"2":["Afghanistan",32,12],"4":["Albania",32,12]}
How can I remove these row numbers without using any Regex trickery?
If the array keys in your PHP array are not consecutive numbers, json_encode() must make the other construct an object since JavaScript arrays are always consecutively numerically indexed.
Use array_values() on the outer structure in PHP to discard the original array keys and replace them with zero-based consecutive numbering:
Example:
// Non-consecutive 3number keys are OK for PHP
// but not for a JavaScript array
$array = array(
2 => array("Afghanistan", 32, 13),
4 => array("Albania", 32, 12)
);
// array_values() removes the original keys and replaces
// with plain consecutive numbers
$out = array_values($array);
json_encode($out);
// [["Afghanistan", 32, 13], ["Albania", 32, 12]]
json_encode() function will help you to encode array to JSON in php.
if you will use just json_encode function directly without any specific option, it will return an array.
Like mention above question
$array = array(
2 => array("Afghanistan",32,13),
4 => array("Albania",32,12)
);
$out = array_values($array);
json_encode($out);
// [["Afghanistan",32,13],["Albania",32,12]]
Since you are trying to convert Array to JSON, Then I would suggest to use JSON_FORCE_OBJECT as additional option(parameters) in json_encode, Like below
<?php
$array=['apple','orange','banana','strawberry'];
echo json_encode($array, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
I want to add to Michael Berkowski's answer that this can also happen if the array's order is reversed, in which case it's a bit trickier to observe the issue, because in the json object, the order will be ordered ascending.
For example:
[
3 => 'a',
2 => 'b',
1 => 'c',
0 => 'd'
]
Will return:
{
0: 'd',
1: 'c',
2: 'b',
3: 'a'
}
So the solution in this case, is to use array_reverse before encoding it to json
I had a problem with accented characters when converting a PHP array to JSON. I put UTF-8 stuff all over the place but nothing solved my problem until I added this piece of code in my PHP while loop where I was pushing the array:
$es_words[] = array(utf8_encode("$word"),"$alpha","$audio");
It was only the '$word' variable that was giving a problem. Afterwards it did a jason_encode no problem.
Hope that helps
Related
This question already has answers here:
Applying a function for each value of an array
(5 answers)
Closed 6 years ago.
Is there util that parses array content without the need of iterating it and parsing each value?
input: ['2','3','7']
output: [2, 3, 7]
This obviously iterates internally, but you don't have to code an iterator:
$output = array_map('intval', $input);
Maps every value in $input to the intval() function and returns the result. For things that cannot be converted into an integer you'll get 0 or for objects, a notice and that value will not be returned.
I can't tell if you want to remove 0 values or not from your comment, but if so:
$output = array_filter(array_map('intval', $input));
You can use array_map
array = ["2","3","4"];
$intArray = array_map('intval', $array);
Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}
This question already has answers here:
Create an assoc array with equal keys and values from a regular array
(3 answers)
Closed 6 years ago.
I have this array:
$a = array('b', 'c', 'd');
Is there a simple method to convert the array to the following?
$a = array('b' => 'b', 'c' => 'c', 'd' => 'd');
$final_array = array_combine($a, $a);
Reference: http://php.net/array-combine
P.S. Be careful with source array containing duplicated keys like the following:
$a = ['one','two','one'];
Note the duplicated one element.
Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
All,
I have an array with hyphens in the key name. How do I extract the value of it in PHP? It returns a 0 to me, if I access like this:
print $testarray->test-key;
This is how the array looks like
testarray[] = {["test-key"]=2,["hotlink"]=1}
Thanks
You have problems:
testarray[] = {["test-key"]=2,["hotlink"]=1}
1 2
You are missing $ used to create variables in php
It is not a valid array format
.
print $testarray->test-key;
1
The => operator is used for objects, not arrays, use [] instead.
Here is how your code should be like:
$testarray = array("test-key" => 2, "hotlink" => 1);
print $testarray['test-key'];
Finally,
See PHP Array Manual
print $testarray["test-key"];
The PHP manual has a good page explaining arrays and how to do things with them:
http://www.php.net/manual/en/language.types.array.php
Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.
As an example I'd like to do the following:
$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange');
$array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry');
// prepend magic
$resulting_array = ('fruit1'=>'cherry',
'fruit2'=>'blueberry',
'fruit3'=>'apple',
'fruit4'=>'orange');
Can't you just do:
$resulting_array = $array2 + $array1;
?
You cannot directly prepend an associative array with a key-value pair.
However, you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.
The syntax is below.
$new_array = array('new_key' => 'value') + $original_array;
Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.
In your situation, you want to use array_merge():
array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));
To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():
array_merge(array($key => $value), $myarray);
Using the same method as #mvpetrovich, you can use the shorthand version of an array to shorten the syntax.
$_array = array_merge(["key1" => "key_value"], $_old_array);
References:
PHP: array_merge()
PHP: Arrays - Manual
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
#Cletus is spot on. Just to add, if the ordering of the elements in the input arrays are ambiguous, and you need the final array to be sorted, you might want to ksort:
$resulting_array = $array1 + $array2;
ksort($resulting_array);
If using Laravel, you can use prepend on a collection instance
collect(['b' => 'b', 'c' => 'c'])->prepend('a','a');
// ['a'=>'a', 'b' => 'b', 'c' => 'c']
https://laravel.com/docs/9.x/collections#method-prepend