I have String which look like this,
1|2|3|4
and I'm creating a array from that string by,
$arr = explode("|", $data['my_list']);
and then from each element of the array i need to pair with another value by creating associative array. After create, it should look like this,
1=>1
1=>2
1=>3
1=>4
so inside a loop I need to create this associative array. Can anybody please explain how to do this
$tempArr = array();
$arr = explode("|", $data['my_list']);
foreach($arr as $item) {
$tempArray['associative_with_key_' . $item] = 5; // where 5 is a new value
}
Related
I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.
Example Array:
$nums = array (
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
What I did but get an empty array
$newArr = [];
foreach ($nums as $value) {
array_merge($newArr, $value);
}
Expectation
$newArr = array(1,2,3,4,5,6,7,8,9)
You could use the function array_merge() this way :
$newArr = array_merge(...$nums)
It would make your code lighter and avoid the use of a foreach loop.
array_merge returns the results of the merge rather than acting on the passed argument like sort() does. You need to be doing:
$newArr = array_merge($newArr, $value);
In PHP I have a dynamic 1-D Array which is like
$array = ['test1', 'test2', ..., 'testn'] And I need to convert this into a multidimensional array where array nesting level will be equal to the number of elements in the 1-D array, and each level will have its index with the name of 1-D array values, so, the output should be something like:
$multidimentional['test1']['test2'][...]['testn'] = [Some Fixed Value] And, after creating the multidimensional array assign a fixed value to it.
So, basically this fixed value needs to be assigned in a multidimensional array which has nesting level as per 1-D array values.
You can simply loop over the elements, assign the element as key to the current array and move on with the child array.
<?php
$array = ['test1', 'test2','test3', 'test4'];
$res = [];
$temp = &$res;
foreach($array as $val){
$temp[$val] = [];
$temp = &$temp[$val];
}
$temp[] = 45; // some fixed value
print_r($res);
Demo: https://3v4l.org/INfR2
I have 2 arrays and want to combine into third array with one array as key and another as value. I tried to use array_combine(), but the function will eliminate all the repeated keys, so I want the result array as a 2d array. The sample array is as below:
$keys = {0,1,2,0,1,2,0,1,2};
$values = {a,b,c,d,e,f,g,h,i};
$result = array(
[0]=>array(0=>a,1=>b,2=>c),
[1]=>array(0=>d,1=>e,2=>f),
[2]=>array(0=>g,1=>h,2=>i)
);
//What i am using right now is:
$result = array_combine($keys,$values);
But it only returns array(0=>g,2=>h,3=>i). Any advice would be appreciated!
You can do it like below:-
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$values = array_chunk($values,count(array_unique($keys)));
foreach($values as &$value){
$value = array_combine(array_unique($keys),$value);
}
print_r($values);
https://eval.in/859753
Yes the above is working and i give upvote too for this but i dont know why you combine into the foreach loop its not necessary. The results are given in only in second line. Can you describe?
<?php
$keys = array(0,1,2,0,1,2,0,1,2);
$values = array('a','b','c','d','e','f','g','h','i');
$v = array_chunk($values,count(array_unique($keys)));
echo "<pre>";print_r($v);
?>
https://eval.in/859759
As a more flexible/robust solution, push key-value pairs into new rows whenever the key's value is already in the currently targeted row. In other words, there will never be an attempt to write a key into a row that already contains that particular key.
This can be expected to be highly efficient because there are no iterated function calls ...no function calls at all, really.
Code: (Demo)
$result = [];
foreach ($keys as $i => $key) {
$counter[$key] = ($counter[$key] ?? -1) + 1;
$result[$counter[$key]][$key] = $values[$i];
}
var_export($result);
I've got an array containing values I wish to use as keys, such as:
$keys = array("first", "second", "third", "fourth");
The count and contents of these values will be changing dynamically within a loop. I want them to become the keys of a multidimensional array, but the count of the keys array will always be changing, so while this would work for that first array of keys:
$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";
Later in the loop the keys may be something like:
$keys = array("first", "second", "gamma", "delta", "theta", "kappa");
So using this in the loop:
$multidimensional[$keys[0]][$keys[1]][$keys[2]][$keys[3]] = "some value";
Will not work, and needs to be dynamic too based on the count of the keys.
I've gone through each of the array functions in the PHP manual and can't seem to find something that fulfills this purpose. Am I totally overlooking something basic here? Maybe some curly brace magic?
There you go...
function setMultidimensionalValue($value, array $keys, array $multidimensional)
{
$node = &$multidimensional;
foreach ($keys as $key)
{
if (!isset($node[$key]))
$node[$key] = null;
$node = &$node[$key];
}
$node = $value;
return $multidimensional;
}
// Example of usage
$multidimensional = array();
var_dump(setMultidimensionalValue('value', array('first', 'second', 'third'), $multidimensional));
Sorry for the confusing title...
I need to perform an array_intersect() against a variable number of arrays. To do this it seems I need to use the call_user_func_array() function, however, this doesn't seem to be working and gives me the error:
Warning: array_intersect() [function.array-intersect]: Argument #1 is not an array in...
But, if I "print_r" the array to make sure then I see that it is an array:
Array ( [0] => arr_0 [1] => arr_1 )
My code (trimmed to just show the broken part):
$i = 0;
$arr_results = array();
foreach($arr_words as $word) {
$arrayname = "arr_".$i;
$$arrayname = array();
while ($row = mysql_fetch_assoc($search)) {
array_push($$arrayname, $row['id']);
}
array_push($arr_results, "$arrayname");
$i++
}
$matches = call_user_func_array('array_intersect',$arr_results);
In the full code I'm populating the arrays in the foreach loop with data obtained from sql queries.
From my comments:
"$arrayname" is a string, not an array. call_user_func_array will pass each element in $arr_results as argument to array_intersect. array_intersect expects arrays as arguments, but each item in $arr_results is a string, not an array.
All you have to do is create an array of arrays instead of array names:
$arr_results = array();
foreach($arr_words as $word) {
$ids = array();
while ($row = mysql_fetch_assoc($search)) {
$ids[] = $row['id'];
}
$arr_results[] = $ids;
}
$matches = call_user_func_array('array_intersect',$arr_results);
I turn $arrayname into an array with $$arrayname = array();
Right, you create a variable, lets say arr_0 which will point to array. But there is still a difference between the variable name arr_0 and the string containing the variable name "arr_0". You create an array of strings, and that just won't work. PHP does not know that the string contains a name of a variable. For example, consider this:
$arr = "arr_0";
echo $arr[0];
Based on your logic, it should output the first element of the array, but it does not, because $arr is a string, not an array, although it contains the name of a variable.
You'd have to use eval, but you really should not. You could also use variable variables again:
array_push($arr_results, $$arrayname);
that would work as well, but as I said, variable variables are confusing and in 99% of the cases, you are better of with an array.