how to create php keys from an arrays values? [duplicate] - php

This question already has answers here:
Create nested array by array of keys
(3 answers)
Closed 6 years ago.
I have an array like so:
$input = array("visit", "outdoor", "parks-trailer");
$input_content = "A Value for last array element for input array."
$another_input = array("visit", "outdoor");
$another_input_content = "A Value for last array element for $input_content array."
And I have some text to assign to the last element of the array, once built.
Basically, what I need is the returned array to be like this:
$output = array(
"visit" => array(
"outdoor" => array(
"A Value for last array element for $input_content array."
"parks-trailer" => "A Value for last array element for input array."
)
)
);
How can I do this from values of an $input array that will always be 1 dimensional.
$content = 'My Value';
$output = array();
$flipped = array_flip($input);
$count = count($input) - 1;
foreach($flipped as $key => $flip)
{
if ($count >= $key)
$output[$key] = $content;
else
$output[$key] = array();
}
The problem here is that array_flip does work, but it doesn't do multidimensional here? And so array_flip transforms to array('visit' => 0, 'outdoor' => 1, 'parks-trailer' => 2), but I'm at a loss on how to get it to do multidimensional array, not singular.
I need to loop through multiples of these and somehow merge them into a global array, the answer given in here is not the same.
So, I need to merge each 1 of these into another array, keeping the values, if they exist. array_merge does not keep the values, array_merge_recursive does not keep the same key structure. How to do this?

I'm not sure sure why you would want such thing, but this is an option:
$ar = ['a', 'b', 'c'];
function arrayMagicFunction($ar, $last_string = 'STRING') {
$ret = $last_string;
$ar = array_reverse($ar);
foreach ($ar as $v) {
$ret = [$v => $ret];
}
return $ret;
}
var_dump(arrayMagicFunction($ar, 'A Value here'));
Output:
array(1) {
'a' =>
array(1) {
'b' =>
array(1) {
'c' =>
string(12) "A Value here"
}
}
}

Related

Get the index of the same value of a array php

I have an associative array like this [this array is combination of two different arrays]:
I combine arrays and via array_combine() function
$products = array_combine($one_array_key,$second_array_values);
$products = array(
"arn1" =>"A",
"arn2" =>"A",
"arn3" =>"A",
"arn4" =>"B",
"arn5" =>"B",
"arn6" =>"B"
);
So As you can see there are two distinct values from array A and B.
I want two arrays consists of it's keys.
Or in other words: Compare values of associative array and matched values's key will be extract to the other array .
So My expected out is:
$A = array("arn1","arn2","arn3");
$B = array("arn4","arn5","arn6");
My code:
$products = array_combine($one_array_key,$second_array_values);
$products_distinct_values = array_count_values($product);
$products_distinct_values_keys = array_keys($products_distinct_values);
foreach ($products as $key => $value)
{
// what should I need write there, to get the x numbers of array(s), containing *key* of the same *value of array*
}
I SUPER would never use this "variable variables" technique in a professional project, but it does satisfy your brief. I will urge you to find the folly in your XY Problem.
Effectively, the snippet below will synchronously iterate over the two related input arrays and create variably-named result arrays to push values into.
Code: (Demo)
$one_array_key = ['A', 'A', 'A', 'B', 'B', 'B'];
$second_array_values = ['arn1', 'arn2', 'arn3', 'arn4', 'arn5', 'arn6'];
foreach ($one_array_key as $index => $value) {
$$value[] = $second_array_values[$index];
}
var_export($A);
echo "\n---\n";
var_export($B);
Output:
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
)
---
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
)
It makes much more sense to have a statically named variable containing keys and related subarrays. This way you can call array_keys() on the result, if you wish, to find out which groups were found in the original input.
Code: (Demo)
$result = [];
foreach ($one_array_key as $index => $value) {
$result[$value][] = $second_array_values[$index];
}
var_export($result);
Output:
array (
'A' =>
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
),
'B' =>
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
),
)
You can use the following PHP code to do that.
<?php
$products = array("arn1"=>"A", "arn2"=>"A", "arn3"=>"A", "arn4"=>"B", "arn5"=>"B", "arn6"=>"B");
$A = array();
$B = array();
foreach ($products as $key => $value)
{
if ($value == "A")
{
array_push ($A, $key);
}
else if ($value == "B")
{
array_push ($B, $key);
}
}
print_r ($A);
print_r ($B);
?>

Split an array into two arrays based on identical values

I have this array:
$arrayAll = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
where the keys are unique - they don't ever repeat. And the value could be either 1 or 2 - nothing else.
And I need to "split" this $arrayAll array into $array1 - that will contain everything with value 1 and $array2 - that will contain everything with value 2 so in the end I will have:
$array1 = [
'156' => '1',
'157' => '1',
'159' => '1',
'161' => '1'
];
and
$array2 = [
'158' => '2',
'160' => '2'
];
and as you can see, I will have the keys from the original array will remain the same.
What is the simplest thing to do to separate the original array like this?
This is probably the simplest way.
Loop it and create a temporary array to hold the values then extract the values to your array 1 and 2.
Foreach($arrayAll as $k => $v){
$res["array" . $v][$k] = $v;
}
Extract($res);
Var_dump($array1, $array2);
https://3v4l.org/6en6l
Updated to use extract and a method of variable variables.
The update means it will work even if there is a value "3" in the input array.
https://3v4l.org/jbvBf
Use foreach and compare each value and assign it to a new array.
$array1 = [];
$array2 = [];
foreach($arrayAll as $key=>$val){
if($val == 2){
$array2[$key] = $val;
}else{
$array1[$key] = $val;
}
}
print_r($array1);
print_r($array2);
Demo
The simplest thing to do is to use a foreach loop.
$array = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
$array1 = [];
$array2 = [];
foreach ($array as $key => $value)
// If value is 1, add to array1
// If value is not 1, add value to array2
if ($value === '1')
$array1[$key] = $value;
else
$array2[$key] = $value;
echo var_dump($array1);
echo '<br>';
echo var_dump($array2);
Use indirect reference:
$arrayAll = array("156"=>"1", "157"=>"1", "158"=>"2", "159"=>"1", "160"=>"2", "161"=>"1");
foreach($arrayAll as $key=>$value) {
$name = "array".$value;
$$name[$key] = $value;
}
echo "<pre>";
print_r($array1);
print_r($array2);
echo "</pre>";
//your array
$yourArray = [
'156' => '1',
'157' => '1',
'158' => '2',
'159' => '1',
'160' => '2',
'161' => '1'
];
With the conditions you mentioned just build two arrays, you can use array_keys with the second parameter that accepts a search value
$array1 = array_keys($yourArray, '1');
$array2 = array_keys($yourArray, '2');
If you don't want to use array_keys, go for an iteration
$array1 = array();
$array2 = array();
foreach($yourArray as $key=>$value){
//will always be 1 or 2, so an if-else is enought
if($value == 1){
$array1[] = $key;
} else {
$array2[] = $key;
}
}
And that's it.
Check this link for array_keys
If you have more than 2 values, the following will work and can be reused for other cases
You want to group them according to the values
$arrayOfValues = array_values($yourArray);
//this returns only the values of the array
$arrayOfUniqueValues = array_unique($arrayOfValues);
//this returns an array with the unique values, also with this u consider
//the posibility for more different values
//also u can get the unique values array on a single line
$arrayIfUniqueValues = array_unique(array_values($yourArray));
The array you will return
$theReturn = array();
foreach($arrayOfUniqueValues as $value ){
//what does this do?
//for each iteration it creates a key in your return array "$theReturn"
//and that one is always equal to the $value of one of the "Unique Values"
//array_keys return the keys of an array, and with the second parameter
//it acceps a search parameter, so the keys it return are the ones
//that matches the value, so here u are getting the array already made
$theReturn[$value] = array_keys($yourArray, $value);
}
The var_dump, in this case, will look like this
array(2) {
[1]=>
array(4) {
[0]=>
int(156)
[1]=>
int(157)
[2]=>
int(159)
[3]=>
int(161)
}
[2]=>
array(2) {
[0]=>
int(158)
[1]=>
int(160)
}
}
Hope my answer helps you, I tried to organize the solutions starting with the shortest/simplest.
Edit:
I forgot you needed the key value too, at least in this solution the array is always referring to the value, like $array1, $array2 or the $key references to the value as in the last solution
The simplest solution for separating an array into others based on the values involves:
Getting its unique values using array_unique.
Looping over these values using foreach.
Getting the key-value pairs intersecting with the current value using array_intersect.
Code:
# Iterate over every value and intersect it with the original array.
foreach(array_unique($arrayAll) as $v) ${"array$v"} = array_intersect($arrayAll, [$v]);
Advantage:
The advantage of this answer when compared to other given answers is the fact that it uses array_unique to find the unique values and therefore iterates only twice instead of n times.
Check out a live demo here.

Get to element in multi-dimensional array using an undetermined number of keys

This is a bit of weird one, but I can't get my head around it. I have a multidimensional array that has an unknown length and unknown number of dimensions. I also have an array of keys like so:
$keys = array(0, 2, 1, 0);
Now, if this array of keys had a determined size I would simply access my multidimensional array like so:
$multidimensional_array[$keys[0]][$keys[1]][$keys[2]][$keys[3]];
The problem is that it doesn't, the length of the keys array will change a lot. Does anyone know of a loop that could iterate across the keys arrays and then access the multidimensional array accordingly?
Assuming such array:
$multidimensional_array = array(
0 => array(
2 => array(
1 => array(
0 => 'value'
)
)
)
);
And these keys:
$keys = array(0, 2, 1, 0);
You can do:
$current = $multidimensional_array;
foreach($keys as $key) {
$current = $current[$key];
}
var_dump($current); //'value'
Edit:
Here's an example with references.
$current = &$multidimensional_array; // <- $current is reference
foreach($keys as $key) {
$current = &$current[$key]; // <- $current is reference again
}
var_dump($current); //'value'
$current = 'otherValue'; // $multidimensional_array[0][2][1][0] value changed to 'otherValue'
unset($current); // remove reference to be sure you won't break something later by an accident
https://3v4l.org/OuAiQ

PHP - Associative arrays: Changing keys for key value pair where value is a class object

I have an associative array of the form:
$input = array("one" => <class object1>,
"two" => <class object2,
... //and so on);
The keys of $input are guaranteed to be unique. I also have a method called moveToHead($key) which moves the $input[$key] element to the 0th location of this associative array. I have few questions:
Is it possible to determine the index of an associative array?
How to move the array entry for corresponding $key => $value pair to the index 0 and retaining the $key as is?
What could be the best possible way to achieve both of the above points?
I was thinking to do array_flip for 2nd point (a sub solution), but later found out that array_flip can only be done when array elements are int and string only. Any pointers?
With a function called array_keys you can determine the index of a key:
$keys = array_flip(array_keys($input));
printf("Index of '%s' is: %d\n", $key, $keys[$key]);
To insert an array at a certain position (for example at the beginning), there is the array_splice function. So you can create the array to insert, remove the value from the old place and splice it in:
$key = 'two';
$value = $input[$key];
unset($input[$key]);
array_splice($input, 0, 0, array($key => $value));
Something similar is possible with the array union operator, but only because you want to move to the top:
$key = 'two';
$value = $input[$key];
unset($input[$key]);
$result = array($key => $value) + $input;
But I think this might have more overhead than array_splice.
The "index" of an associative array is the key. In a numerically indexed array, the "key" is the index number.
EDIT: I take it back. PHP's associative arrays are ordered (like Ordered Maps in other languages).
But perhaps what you really want is an ordered array of associative arrays?
$input = array(array("one" => <class object1>),
array("two" => <class object2>)
//...
);
Here's what I came up with:
$arr = array('one' => 'Value1', 'two' => 'Value2', 'three' => 'Value3');
function moveToHead($array,$key) {
$return = $array;
$add_val = array($key => $return[$key]);
unset($return[$key]);
return $add_val + $return;
}
print_r(moveToHead($arr,'two'));
results in
Array
(
[two] => Value2
[one] => Value1
[three] => Value3
)
http://codepad.org/Jcb6ebxZ
You can use internal array pointer functions to do what you want:
$input = array(
"one" => "element one",
"two" => "element two",
"three" => "element three",
);
reset($input); // Move to first element.
echo key($input); // "one"
You can unset the element out and put it in the front:
$input = array(
"one" => "element one",
"two" => "element two",
"three" => "element three",
);
$key = "two";
$element = $input[$key];
unset($input[$key]);
// Complicated associative array unshift:
$input = array_reverse($input);
$input[$key] = $element;
$input = array_reverse($input);
print_r($input);

Remove duplicated values function

function remove_values($arr){
$_a = array();
while(list($key,$val) = each($arr)){
$_a[$val] = 1;
}
return array_keys($_a);
}
i can't follow the above function well.i don't know what's the effect of $_a[$val] = 1; anyone can explain it to me thank you
For the purpose of the function, Why not just use array_unique($array)?
Like this
function remove_values($arr){
return array_keys(array_unique($arr));
}
Update:
Ok, Since you are trying to learn. Here is the explanation for the function in the post
function remove_values($arr){
$_a = array(); //Creates a temporary array to store matching
while(list($key,$val) = each($arr)){ //till their is item is array, loop it
$_a[$val] = 1; //Store in the temporary array with array's values as index, thus eliminating the duplicates
//^ Here storing with the value as index IS THE KEY
}
return array_keys($_a); //return only the keys, which in fact are the unique values
}
Well all this does is to insert the value into the key of an array. Since all keys are unique in an array, you will remove all duplicates.
array_keys() simply gives back that array in it's ordinary form.
Example:
$arr = array('red', 'green', 'red');
$arr = remove_values($arr);
gives
array( 'red' => 1,
'green' => 1);
which results in
array('red', 'green');
since "red" can only be a keyvalue once.
Very nice function actually.
$_a[$val] = 1;
makes every element to be signed once, so returned once meaning that duplicates are removed. Than the array_keys($_a) function rebuilds and sorts the array. I liked it.
its assign the value 1 to value part. for ex:
<?php
function remove_values($arr){
$_a = array();
while(list($key,$val) = each($arr)){
$_a[$val] = 1;
}
print_r($_a);
return array_keys($_a);
}
$arr = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
$sed = remove_values($arr);
print_r($sed);
?>
It return two array values:
Array
(
[apple] => 1
[banana] => 1
[cranberry] => 1
)
Array
(
[0] => apple
[1] => banana
[2] => cranberry
)
Now tis easy for you to understand the effect of value '1'.

Categories