I have this normal array name $arr..
and trying to push something on the array using array_push() function.. like array_push( $arr['alerts_data'], 999 );
It produces this output:
Array
(
[alerts_data] => Array
(
[0] => 169
[1] => 175
[2] => 111
[3] => 48
[4] => 999
)
)
When i use json_encode I got:
{"alerts_data":[169,175,111,48,111,999]}
BUT, when I try to unset() something from $arr like:
unset( $arr['alerts_data'][4] );// will remove removes the 999
and then use the json_encode again, I got this json object
{"alerts_data":{"0":169,"1":175,"2":111,"3":48}}
What's wrong in here? can you tell? I want to achieve the first encoded json above by using the unset() function.
Yes, it's because the array keys aren't consecutive anymore, so it's treated as an associative array, and PHP associative arrays become JavaScript objects, because JavaScript does not have associative arrays.
Use array_splice() to cleanly remove elements from the array.
You have a gap in your keys (it goes from 3 to 5), so an object must be created for it to be valid. Two possible solutions:
array_splice($arr['alerts_data'], 4, 1);
unset($arr['alerts_data'][4]);
$arr['alerts_data'] = array_values($arr['alerts_data']);
Related
When a print_r() an array $stats, I get the following:
Array ( [0] => Array ( [like] => 71 [dislike] => 372 [total] => 443 [like_s] => 78 [dislike_s] => 291 [total_s] => 369 [final] => 11 ))
I want to get the [dislike_s] value and put it into a variable.
I have attempted this:
$statss = $stats['dislike_s'];
But it did not work. I have also tried $statss = $stats['dislike_s'][0]; without result.
What am I doing wrong?
You are missing a level of your array
Array ( [0] => Array ( [like] => 71
//^ this level
Also you are using the wrong variable, as you said your array is stored in $stats so
$total_revision = $stats[0]['dislike_s'];
$stats is a two dimensional Array, i.e. it is an array of arrays. You can see this from the output of print_r. You have something that looks like `Array ( [0]=>Array(...)). Therefore, when accessing an element of the inside array, you can think of it like this:
$inner_array=$stats[0];
$total_revisions=$inner_array['dislike_s'];
Php gives you a shorthand for combining these steps(pretty much all languages do) and it looks like $total_revisions=$stats[0]['dislike_s'] but intuitively it's the same thing. You're saying "in the array $stats[0] give back the value of array element 'dislike_s'"
I'm trying to figure out why it is that I cannot access the follow array with this statement:
var_dump($thevar[0]['product_id']);
Array
(
[d142d425a5487967a914b6579428d64b] => Array
(
[product_id] => 253
[variation_id] =>
[variation] =>
[quantity] => 1
[data] => WC_Product Object
(
[id] => 253
[product_custom_fields] => Array
(
[_edit_last] => Array
(
[0] => 1
)
[_edit_lock] => Array
(
[0] => 1345655854:1
)
[_thumbnail_id] => Array
(
[0] => 102
)
I can, however, access the 'product_id' using the dynamically created array name:
print_r($thevar['d142d425a5487967a914b6579428d64b']['product_id']);
The issue is, I don't know what that dynamic name is going to be on the fly...
There are several options for such scenarios.
Manually iterate over the array
You can use reset, next, key and/or each to iterate over the array (perhaps partially).
For example, to grab the first item regardless of key:
$item = reset($thevar);
Reindex the array
Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:
$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed
Iterate with foreach
This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.
foreach($thevar as $item) {
// do something with $item
}
If the array key is dynamic you might find the PHP function array_keys() useful.
It will return an array of the keys used in an array. You can then use this to access a particular element in the array.
See here for more:
http://php.net/manual/en/function.array-keys.php
Because PHP array are associative therefor you have to access them by key.
But you may use reset($thevar) to get first item.
Or array_values():
array_values($thevar)[0]
Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:
$thevar[ array_keys($thevar)[0]]
I'm trying to store an array ($temp) into the $data array, where key is prices.
$data['prices'] = $temp;
However, PHP converts the array into string instead and is throwing me and error.
Notice: Array to string conversion
Is $data = array('prices' => $temp); the only solution?
edit:
I found my mistake. Yes, $data was used previously as a string that's why PHP is converting the input into string.
Problem 2, doing a print_r on $data['prices'] = $xml->result->Prices->Price, shows only 1 set of array. But I am able to retrive 2 sets of result by doing a foreach loop on $data['prices']. Why is that so?
Content of $temp http://pastebin.com/ZrmnKUPB
Let me be more clear..
The full xml object I'm trying to extract information from: http://pastebin.com/AuMJiyrw
I'm only interested in the price array (Price_strCode and Price_strDescription) and store them in $data['prices']. End result something like this:
Array(
[0] => (
[Price_strCode] => 0001
[Price_strDescription] => Gold
)
[1] => (
[Price_strCode] => 0002
[Price_strDescription] => Silver
)
)
Unless you are doing some other array to string conversion elsewhere, the array is actually being stored as another array.
$data['prices'] will be an array, which can be accessed as $data['prices']['key'].
This is not possible, I have been doing this always and it works fine. You must be doing something else somewhere which is causing your array to convert to strong. share your code here
I have an array which prints like this
Array ( [0] => 1691864 [1] => 7944458 [2] => 9274078 [3] => 1062072 [4] => 8625335 [5] => 8255371 [6] => 5476104 [7] => 6145446 [8] => 7525604 [9] => 5947143 )
If I json_encode($thearray) I get something like this
[1691864,7944458,9274078,1062072,8625335,8255371,5476104,6145446,7525604,5947143]
Why the name is not encoded (e.g 0, 1 , 2 , 3 etc) ? and how should I do to make it appear in the json code?
the full code is below
$ie = 0;
while($ie 10)
{
$genid = rand(1000000,9999999);
$temp[$ie] = $genid ;
$ie++;
}
print_r($temp);
$temp_json = json_encode($temp);
print_r($temp_json);
You can force that json_encode uses an object although you’re passing an array with numeric keys by setting the JSON_FORCE_OBJECT option:
json_encode($thearray, JSON_FORCE_OBJECT)
Then the returned value will be a JSON object with numeric keys:
{"0":1691864,"1":7944458,"2":9274078,"3":1062072,"4":8625335,"5":8255371,"6":5476104,"7":6145446,"8":7525604,"9":5947143}
But you should only do this if an object is really required.
Use this instead:
json_encode((object)$temp)
This converts the array into object, which when JSON-encoded, will display the keys.
If you are storing a sequence of data, not a mapping from number to another number, you really should use array.
Because those are just the indices of the array. If you want to add some kind of name to each element then you need to use an associative array.
When you decode that JSON array though it will come back out to 0, 1, 2, 3 etc.
This is defined behaviour. The array you show is a non-associative, normally indexed array. Its indexes are implicitly numeric.
If you decode the array in PHP or JavaScript, you will be able to access the elements using the index:
$temp_array = json_decode($temp_json);
echo $temp_array[2]; // 9274078
I've Googled it for two days, and tried looking at the PHP manual, and I still can't remember that function that aligns the key values for PHP arrays.
All I'm looking for is the function that takes this:
Array
(
[0] => 1
[3] => 2
[4] => 3
[7] => 4
[9] => 5
)
And converts it into this:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Basically, the array is first sorted by key (their values attached to them stay with them), then all the keys are set to all the counting numbers, consecutively, without skipping any number (0,1,2,3,4,5,6,7,8,9...). I saw it being used with ksort() a few months ago, and can't see to remember or find this elusive function.
Well, you see, this one is hard, because the general description on the PHP array functions page does not say that this function does what you're looking for.
But you can sort the array using ksort(), and then use this: array_values() . From the page from the PHP manual:
array_values() returns all the values from the input array and indexes numerically the array.
You can use array_merge:
$array = array_merge($array);
It will reindex values with numeric keys.
Update: Using array_values as proposed in #LostInTheCode's answer is probably more descriptive.
function array_reset_index_keys($array)
{
$return = array();foreach($array as $k => $v){$return[] = $v;}return $return;
}
And then use like a regular function, should re index the array
you can also use native functions such as array_values which returns the values of an array into a single dimension array, causing it to be re indexed .