using array_keys and getting unexpected result - php

I have an array that is assigned to $elements. When I use array_keys to get the keys, I get what you would expect.
print_r(array_keys($elements));
Results in:
Array
(
[0] => anchor-namecontentblock_areaBlock0contentblock11_1
[1] => anchor-namecontentblock_areaBlock0contentblock22_1
[2] => anchor-namecontentblock_areaBlock0contentblock33_1
...
But when I try to use array_keys with a search value, I get an empty array.
print_r(array_keys($elements, "anchor-namecontentblock_areaBlock0contentblock11_1"));
Should the result not be:
Array
(
[0] => 0
)
Am I missing something?

You're doing the wrong array_keys search. Your anchor-name... values are KEYS in the original array, not VALUES. As such, your array_keys search argument is useless - it'll be searching the values of the original array, e.g.
$foo = array(
'anchor-namecontentblock_areaBlock0contentblock11_1' => 'somevalue'
etc..
searched by array_keys---------^^^^^^^^^^
You'd need do something more like:
$results = array_search('anchor-name...', array_keys($elements)));
^^^^^^^^^^^^^
instead.

Specifying a search parameter to array_keys allows you to retrieve the key(s) corresponding to one or more values in your array. You're passing it one of your array keys, so the function is returning no results.

Related

PHP - Store an array returned by a function in an already existing array, one by one

Very simplified example:
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);
I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):
Array
(
[0] => hello
[1] => world
[2] => Array
(
[0] => First
[1] => Second
[2] => Third
)
)
Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.
But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!
You can use array_merge,
$arr = array_merge($arr, returnArray());
will result in
Array
(
[0] => hello
[1] => world
[2] => First
[3] => Second
[4] => Third
)
This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because
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.
You are appending the resulting array to previously created array. Instead of the use array merge.
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);

FETCH_ASSOC removes indexes in the wrong array

I am creating a small web application and I am running on two arrays - one retrieved by simplexml_load_file and the other generated by query to database. I have a little problem with the latter - I need to create an associative array that I can reference through indexes. For that I do something like that.
$stmt->execute();
$db = $stmt->fetchAll(PDO::FETCH_ASSOC);
The array should therefore look like this:
Array (
['element'] => value,
)
It looks like this:
Array (
[0] => Array (
['element'] => value,
)
)
The only thing I noticed was that in the query the records are created so
Array (
[0] => Array (
['element'] => value,
[0] => value
)
)
My solution removes indexes inside the first array, in this example it will remove the line [0] => value, although the main index will remain. How can I change this to result in a full associative associative array? I mention that I want to display all the records from the query, the same fetch () works, although it displays one record (last) from the query.
Try to change
From
$db = $stmt->fetchAll(PDO::FETCH_ASSOC);
To
$db = $stmt->fetch(PDO::FETCH_ASSOC);
PDOStatement::fetch — Fetches the next row from a result set
While PDOStatement::fetchAll — Returns an array containing all of the result set rows
The 0 means row one. If you want to process only one row use the current function on the array which will give you expected results

How do I reorganize an array in PHP?

I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.

PHP built in array function

Lets say I end up with an array like such:
Array ( [0] => Array ( [0] => user
[1] => pass
)
)
maybe as a result of passing an array through a function and using func_get_args()
In this case, I would want to get rid of the initial array, so I just end up with:
Array ( [0] => user
[1] => pass
)
I know I could make a function to accomplish this, and push each element into a new array, however, is there some built in functionality with PHP that can pull this off?
$new_array = $old_array[0];
...
array_pop() will pop the last (first, if only 1 is present) element.
Just take the value of the first element of the "outer" array.
I would recommend array_shift as it removes and returns the first element off of the beginning of the array.

PHP Aligning Array Key Values

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 .

Categories