some "simple" problem:
I've this array;
$myArray = array(
'FOO',
'BAR,
);
i want :
$mayArray = array(
'FOO' => array(),
'BAR' => array(),
);
in the moment iam doing it with an foreach:
foreach ($myArray as $key => $val) {
$newArray[$val] = array();
}
$myArray = $newArray;
is there an easyer way ? ;-)
The way you have is pretty easy to understand. But you can also do this:
$myArray = array_fill_keys($myArray, array());
Docs here: http://us2.php.net/manual/en/function.array-fill-keys.php
You can use array_fill_keys, here is example:
$myArray = array_fill_keys($myArray, array());
Related
I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);
I have this array in PHP
$fields = array(
0 => array(
'field1' => 'something1',
'field2' => 'something2'
)
)
And I need it to look like this
$fields = array(
'fields1' => 'something1',
'fields2' => 'something2'
)
What function code can I use to get rid of the 0 index in the example?
You can loop through like this...
Create new array
$newArray = [];
Then loop through
foreach($fields as $field){
if(is_array($field)){
foreach($field as $key => $value){
$newArray[$key] = $value;
}
}
}
just take the '0' element from fields:
$fields=$fields[0];
Simple
$fields = reset($fields);
Or
$fields = array_shift($fields);
Create an array, loop through $fields, and merge whatever items are there with the created array.
$final_array = array();
foreach ($fields as $field)
{
$final_array = array_merge($final_array, $field);
}
$fields = $final_array;
This will be able to handle any number of items in either level of the array and compact them into a one-level array.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); $list = iterator_to_array($it,false);
Use this to get ride of any extra levels.
Will gives you what you want
I have this php associative array.
array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
)
I would like to convert it into a json output using json_encode() that looks like this;
[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]
How can this be done? The challenging part to me seems like how to add the Location_name and Link_name in front. Thank you very much.
<?php
// original array
$a = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
// transform
$b = array();
foreach($a as $key=>$value) {
$b[] = array('Location_name'=>$key, 'Link_name'=>$value);
}
// output
echo json_encode($b);
?>
Result:
[{"Location_name":"Location_1","Link_name":"Link_1"},{"Location_name":"Location_2","Link_name":"Link_2"}]
You Can use StdClass anonymous Objects.
<?php
$newArray = array();
$array = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
foreach ($array as $key => $value) {
$object = new StdClass();
$object->Location_name = $key;
$object->Link_name = $value;
$newArray[] = $object;
}
var_dump(json_encode($newArray));
So first things first:
convert it into a json output using json_encode() that looks like this
This is not possible. json_encode just encodes arrays to JSON, you need to do the formatting work yourself.
And on that note
array_map should do the trick.
Try this:
$arr = array(
'Location_1' => 'Link_1',
'Location_2' => 'Link_2'
);
$output = array_map(
function( $key, $val ){
return array(
"Location_name" => $key,
"Link_name" => $val
);
}, array_keys( $arr ), $arr );
echo json_encode( $output );
Hello how can i convert string to array but it should be in nested format. like i show in the example.
first i tried to explode "/" then i try static variable in foreach loop.. but no luck.
i'm beginner & still confused how to do this..
FROM
$str = 'first/second/third';
To
array(
'first' => array(
'second' => array(
'third' => array(
)
)
)
);
Apply cleverness :p
$keys = explode("/",$str);
$result = array();
$ref = &$result;
foreach($keys as $key) {
$ref[$key] = array();
$ref = &$ref[$key];
}
unset($ref); // delete the reference
I have a nested assocative array which might look something like this:
$myarray = array(
['tiger'] => array(
['people'], ['apes'], ['birds']
),
['eagle'] => array(
['rodents'] => array(['mice'], ['squirrel'])
),
['shark'] => ['seals']
);
How can I loop through the first layer (tiger, eagle, shark) in a random order and ensure that I cover them all in my loop? I was looking at the PHP function shuffle();, but I think that function messes up the whole array by shuffling all layers.
You can randomly sort an array like this, it will keep the keys and the values
<?php
$myarray = array(
'tiger' => array(
'people', 'apes', 'birds'
),
'eagle' => array(
'rodents' => array('mice', 'squirrel')
),
'shark' => 'seals'
);
$shuffleKeys = array_keys($myarray);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $myarray[$key];
}
print_r($newArray);
You can get the keys using array_keys(). Then you can shuffle the resulting key array using shuffle() and iterate through it.
Example:
$keys = array_keys($myarray);
shuffle($keys);
foreach ($keys as $key) {
var_dump($myarray[$key]);
}
According to my test, shuffle only randomizes 1 layer. try it yourself:
<?php
$test = array(
array(1,2,3,4,5),
array('a','b','c','d','e'),
array('one','two','three','four','five')
);
shuffle($test);
var_dump($test);
?>