This question already has answers here:
Using a string path to set nested array data [duplicate]
(8 answers)
Closed 2 years ago.
I want to find a workaround for the following problem:
I have n vectors(unique), like the following: ("val1", "val2", "val3", ..., "valn" ).
Each vector's length is different.
I want to add any of those in a new array, but using the vector values(val1,val2,val3) elements as sub-elements recursively for the new array, taken from the main vector(val1 => val+1 => val+2 => val+3 => ... val+n => solution), and the last element of the vector is an integer or a string(not a sub-array/vector as the others), which will match with the last element of the new array, and it's new array's soluton/target.
The workaround solution I am applying right now is this:
Let's suppose the target(solution) is the end value of the array(an integer or string).
In this case I suppose to work on a vector with 4 elements, where the last one is the solution.
$vector = array("val1", "val2", "val3", "target");
$count = count($vector);
$new_array = array();
switch($count){
case 1:
....
case 4:
$new_array[$vector[0]][$vector[1]][$vector[2]] = $vector[3];
/*New array will be
$new_array = [
val1 =>
val2 =>
val3 => "target"
];
*/
break;
}
The vectors I am using are many and with different sizes, so the solution/target can be in the 1st element, second, third and so on, so I applied in my switch any cases from 0 to 5 for example, working as wrote above.
I think there could be a better solution, to loop inside a for(or better, a while) cycle
But I am currently having no ideas on how it should be, and I didn't find any workaround in the web.
Does anyone have a soluton for this?
Thanks in advance
You can build the resulting array starting from the most recent nested element:
$vector = array("val1", "val2", "val3", "val4", "val5", "target");
$new_array = array_pop($vector);
foreach(array_reverse($vector) as $val) {
$new_array = [$val => $new_array];
}
print_r($new_array);
Hi You can change your code like it:
<?php
$vector = array("val1", "val2", "val3", "val4", "val5", "target");
$count = count($vector);
$new_array = array();
$new_array[$vector[$count - 2]] = $vector[$count - 1];
for ($i=($count - 3); $i >= 0; $i--) {
$temp_array = array();
$temp_array[$vector[$i]] = $new_array;
$new_array = $temp_array;
}
print_r($new_array);
And the result will be like it:
Array
(
[val1] => Array
(
[val2] => Array
(
[val3] => Array
(
[val4] => Array
(
[val5] => target
)
)
)
)
)
Related
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 9 months ago.
I have this array. I want to get the array values to a same array,how can I achieve that?
Array
(
[0] => Array
(
[referrer_id] => usr157
)
[1] => Array
(
[referrer_id] => usr42
)
)
I want this array to be
array("usr157", "usr42")
use array_walk_recursive to achieve the result as follows
<?php
$main = [];
$ref =
[
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
array_walk_recursive($ref, function ($item, $key) use(&$main) {
$main[] = $item;
} );
print_r($main);
You can check that out here
You can just access the array components like this:
// The next line just recreates your example array into a variable called $x:
$x = array(array('referrer_id' => 'usr157'), array('referrer_id' => 'usr42'));
$result = array($x[0]['referrer_id'], $x[1]['referrer_id']);
print_r($result); //print the result for correctness checking
$result will be the output array you wanted.
Using $x[0], you refer the first element of your input array (and hence, $x[1] the second one, ...). Adding ['referrer_id'] will access its referrer_id key. The surrounding array(...) puts the values into an own array.
You can "automate" the whole thing in case you have a bigger input array using a loop.
You may use array_column to achieve that
$flatten = array_column($array, 'referrer_id');
You can also use array_map and array_values together.
$array = [
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
$flatten = array_map(function($item) {
return array_values($item)[0];
}, $array);
var_dump($flatten);
Also you can use the one-liner if you're using latest version of php that support arrow function
$flatten = array_map(fn($item) => array_values($item)[0], $array);
Or without array_values, you may specify the key
$flatten = array_map(fn($item) => $item['referrer_id'], $array);
You can see the demo here
I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}
This question already has answers here:
How to get an array of specific "key" in multidimensional array without looping [duplicate]
(4 answers)
Closed 1 year ago.
I have a multidimensional array, that has say, x number of columns and y number of rows.
I want specifically all the values in the 3rd column.
The obvious way to go about doing this is to put this in a for loop like this
for(i=0;i<y-1;i++)
{
$ThirdColumn[] = $array[$i][3];
}
but there is an obvious time complexity of O(n) involved here. Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
For example (this does not work offcourse)
$ThirdColumn = $array[][3]
Given a bidimensional array $channels:
$channels = array(
array(
'id' => 100,
'name' => 'Direct'
),
array(
'id' => 200,
'name' => 'Dynamic'
)
);
A nice way is using array_map:
$_currentChannels = array_map(function ($value) {
return $value['name'];
}, $channels);
and if you are a potentate (php 5.5+) through array_column:
$_currentChannels = array_column($channels, 'name');
Both results in:
Array
(
[0] => Direct
[1] => Dynamic
)
Star guests:
array_map (php4+) and array_column (php5.5+)
// array array_map ( callable $callback , array $array1 [, array $... ] )
// array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
Not yet. There will be a function soon named array_column(). However the complexity will be the same, it's just a bit more optimized because it's implemented in C and inside the PHP engine.
Try this....
foreach ($array as $val)
{
$thirdCol[] = $val[2];
}
Youll endup with an array of all values from 3rd column
Another way to do the same would be something like $newArray = array_map( function($a) { return $a['desiredColumn']; }, $oldArray ); though I don't think it will make any significant (if any) improvement on the performance.
You could try this:
$array["a"][0]=10;
$array["a"][1]=20;
$array["a"][2]=30;
$array["a"][3]=40;
$array["a"][4]=50;
$array["a"][5]=60;
$array["b"][0]="xx";
$array["b"][1]="yy";
$array["b"][2]="zz";
$array["b"][3]="aa";
$array["b"][4]="vv";
$array["b"][5]="rr";
$output = array_slice($array["b"], 0, count($array["b"]));
print_r($output);
I have an array:
$ids = array(1 => '3010', 2 => '10485', 3 => '5291');
I want to create a new array that takes the values of the $ids array and sets them as the keys of a new array, having the same value.
The final array would be:
$final = array('3010' => 'Green', '10485' => 'Green', '5291' => 'Green');
This will be used in apc_add().
I know I can accomplish this by looping thru it.
$final = array();
foreach($ids as $key => $value):
$final[$value] = 'Green';
endforeach;
But I was wondering if there was php function that does this without having to use a forloop, thanks!
You are looking for array_fill_keys.
$final = array_fill_keys($ids, "Green");
However, be aware that strings that are decimal representations of integers are actually converted to integers when used as array keys. This means that in your example the numbers that end up as keys in $final will have been transformed to integers. Most likely won't make a difference in practice, but you should know about it.
You can do with array_fill_keys this way:
$final = array_fill_keys($ids, "Green");
I need to have this output
Array
(
[id:>] => 0
[isonline] => 0
[userclass_id] => 3
)
and I am getting this output with this code:
$pr = array('id:>'=>$id,'isonline'=>'0','userclass_id'=>'3');
print_r($params);
This is good. But i want to pop new elements to array one by one.
While i am using this code:
$params = array();
array_push($params,array('userclass_id'=>'3')); // Members
array_push($params,array('isonline'=>'0')); // Online
array_push($params,array('id:>'=>$id));
I am getting this output:
Array
(
[0] => Array
(
[userclass_id] => 3
)
[1] => Array
(
[isonline] => 0
)
[2] => Array
(
[id:>] => 0
)
)
I want to dynamically add new element but also want to have first output. Thanks for your helps.
The order of key values in an associative array don't matter. Therefore you don't need to array_push or array_unshift. The only thing you need to do is associate a key to the value you want (or vice-versa). So you would write the following to dynamically add values to the $params array.
$key = "my_id:2";
$value = "23";
$params[$key] = $value;
Yep, no shifting, or pushing... just add the $key between the square brackets and your all good.
$element = array();
$element['userclass_id'] = 3;
$element['isoline'] = 0;
$element['id:>'] = $id;
$params[] = $element
You are using array_push which adds elements to the end of the array. You should be using array_unshift, which will prepend new items to the beginning of the array.
When programatically relying on array order in php... array_pop, array_push, array_shift, and array_unshift are your friends. Know them... love them...
php manual entry for array_unshift
erenon's answer is probably better, but if you really want to add the sub-array one element at a time:
$params = array();
array_unshift($params,array('userclass_id'=>'3')); // Members
$params[0]['isonline'] = 0; // Online
$params[0]['id:>'] = $id;
This works because array_unshift puts elements at the beginning of the array, therefore the new sub-array will always be element 0.
For performance reasons, you may wish to do this instead, so that the elements are not being constantly renumbered:
$params = array();
$params[] = array('userclass_id'=>'3'); // Members
end($params); // Move to the new element
$key = key($params); // Get the key of the new element
$params[$key]['isonline'] = 0; // Online
$params[$key]['id:>'] = $id;
What was happening is that you were pushing your a new array onto the current array instead of merging your new array into your old array.
$params = array();
$params = array_merge($params, array('userclass_id' => 3)); // Members
$params = array_merge($params, array('isonline'=>'0')); // Online
$params = array_merge($params, array('id:>' => $id));
Or even better yet you can just call array_merge once and pass it all the values
$params = array_merge($params, array('userclass_id' => 3), array('isonline' => '0'), array('id:>' => $id));
Another way to get your desired output would be just assigning the keys directly on the array.
$params = array();
$params['userclass_id'] = 3;
$params['isoline'] = 0;
$params['id:>'] = $id;
And probably the best way of doing things is just to assign the keys when the array is created.
$params = array(
'userclass_id' => 3,
'isoline' => 0,
'id:>' => $id
);
How about just
$aParams[] = array(
'userclass_id' => 3,
'isoline' => 0,
'id:>' => $id
);
I'm a big fan of assigning all the values in an array entry this way, vs. individual assignment statements.