I am having this array :
array(
0 => array("name", "address", "city"),
1=> array( "anoop", "palasis", "Indore"),
2=> array( "ravinder", "annapurna", "Indore")
)
and i want to make this array in this way :
array(
0 => array("name" = >"anoop" , "address" = >"palasia", "city" = >"Indore"),
1 => array("name" = >"ravinder" , "address" = >"annapurna", "city" = >"Indore")
)
The modern way is:
$data = array_column($data, 'value', 'key');
In your case:
$data = array_column($data, 1, 0);
Use array_combine. If $array contains your data
$result = array(
array_combine($array[0], $array[1]),
array_combine($array[0], $array[2])
);
In general
$result = array();
$len = count($array);
for($i=1;$i<$len; $i++){
$result[] = array_combine($array[0], $array[$i]);
}
If your data are in $array:
$res = array();
foreach ($array as $key=>$value) {
if ($key == 0) {
continue;
}
for ($i = 0; $i < count($array[0]); $i++) {
$res[$array[0][$i]] = $value[$i];
}
}
The result is now in $res.
Here is a function that you can use:
function rewrap(Array $input){
$key_names = array_shift($input);
$output = Array();
foreach($input as $index => $inner_array){
$output[] = array_combine($key_names,$inner_array);
}
return $output;
}
Here is a demonstration:
// Include the function from above here
$start = array(
0 => array("name", "address", "city"),
1 => array("anoop", "palasis", "Indore"),
2 => array("ravinder", "annapurna", "Indore")
);
print_r(rewrap($start));
This outputs:
Array
(
[0] => Array
(
[name] => anoop
[address] => palasis
[city] => Indore
)
[1] => Array
(
[name] => ravinder
[address] => annapurna
[city] => Indore
)
)
Note: Your first array defined index 1 twice, so I changed the second one to 2, like this:
array(0 => array("name", "address", "city"), 1 => array("anoop", "palasis", "Indore"),2 => array("ravinder", "annapurna", "Indore"))
That was probably just a typo.
Assuming that you are parsing a CSV file, check out the answers to this question:
Get associative array from csv
Related
I have data in the form:
$data = Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 3 )
I want to convert it to:
$x = [[1], [2], [3], [4]];
I do not know how to do this?
I'm using the library PHP-ML ( http://php-ml.readthedocs.io/en/latest/machine-learning/regression/least-squares/ ).
If you want to create array from values, you can do it this way:
$x = [];
foreach($data as $key => $value) {
array_push($x, $value);
}
If you want to create array of arrays from values you can edit it like this:
$x = [];
foreach($data as $key => $value) {
array_push($x, [$value]);
}
$data = array(1,4,3,3);
$x = '[['.implode('], [', $data).']]';
echo $x;
$data = array(0 => "0", 1 => "1", 2 => "2", 3 => "3");
$output;
$halt = count($data) - 1;
for($i = 0; $i < count($data); $i++){
if($i==$halt){
$output.="[".$data[$i]."]";
}else{
$output.="[".$data[$i]."]".", ";
}
}
$x = "[".$output."]";
echo $x;
Like so?
But why change array to array?
Ahhh I see, You want it in a json format?*
$array = array( 0 => [1], 1 => [2] , 2 => [3], 3 => [3] );
$x = json_encode($array, JSON_HEX_APOS);
echo $x;
[[1],[2],[3],[3]]
I want to combine several arrays into one, they are the result of a form post with an unknown number of elements, eg:
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
What i want is to make a function that takes these arrays as an input and produces a single output, like
$elements = [['id'=>53,'name'=>'fire','temp'=>500] , ['id'=>54,'name'=>'water','temp'=>500] , ['id'=>55,'name'=>'earth','temp'=>500]]
I came up with the following solution:
function atg($array) {
$result = array();
for ($i=0;$i<count(reset($array));$i++) {
$newAr = array();
foreach($array as $index => $val) {
$newAr[$index] = $array[$index][$i];
}
$result[]=$newAr;
}
return $result;
}
It can be called like
$elements = atg(['id' => $ids, 'name' => $names, 'temp' => $temps]);
And it produces the right output. To me it seems a bit overly complicated though, and I'm sure this is a common problem in PHP for form posts, combining seperate fields into a single array per item. What would be a better solution?
You can loop through all of your 3 arrays at once with array_map(). There you can just return the new array with a value of each of the 3 arrays, e.g.
$result = array_map(function($id, $name, $temp){
return ["id" => $id, "name" => $name, "temp" => $temp];
}, $ids, $names, $temps);
Use below code:-
$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
$result = [];
foreach($ids as $k=>$id){
$result[$k]['id'] = $id;
$result[$k]['name'] =$names[$k];
$result[$k]['temp'] = $temps[0];
}
echo '<pre>'; print_r($result);
output:-
Array
(
[0] => Array
(
[id] => 53
[name] => fire
[temp] => 500
)
[1] => Array
(
[id] => 54
[name] => water
[temp] => 500
)
[2] => Array
(
[id] => 55
[name] => earth
[temp] => 500
)
)
If you are ok with a destructive solution, array_shift could do the trick :
$elements = array();
while (!empty($ids)) {
$elements[] = array(
'id' => array_shift($ids),
'name' => array_shift($names),
'temp' => array_shift($temps),
);
}
If you want to make a function, using the same arguments than your example, a solution could be
function atg($array) {
$elements = array();
while (!empty($array[0])) {
$new_element = array();
foreach ($array as $key_name => $array_to_shift) {
$new_element[$key_name] = array_shit($array_to_shift);
}
$elements[] = $new_element;
}
return $elements;
}
$result[$ids]['name'] = $names[0];
$result[$ids]['temp'] = $temps[0]
input array
$input = array (
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
needed output form
$target_output = array (
"audi" => array ( "tokyo" => 1, "barcelona" => 2, "paris" => 7 ),
"ford" => array ( "london" => 3, "prag" => 6 )
);
notes 1:
number of groups are dynamic (user input). For example, additional to
"audi" and "ford"; there could be also "toyota", "mercedes".
Each groups has 3 subinfo: 1-name , 2-locations and 3-quantities for
locations.
Sequences in input are always same. 1st name, 2nd locations, 3rd
quantities.
Each group has proper order number always in input. (such as
"group_name_1 or group_locations_4)
notes 2: I've read array functions again. And tried various codes but I even couldn't get close.
Can you please help me.
assuming that group_name_x, group_locations_x and group_quantities_at_locations_x keys alwas exists in your $input array
$input = array(
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
$new_array = array();
foreach ($input as $key => $val) {
if (strpos($key, 'group_name') !== false) {
$new_array[$val] = array();
$group_no = $key[strlen($key) - 1];
$location_array = explode(',', $input["group_locations_{$group_no}"]);
$group_quantities_array = explode(',', $input["group_quantities_at_locations_{$group_no}"]);
$new_array[$val] = array_combine($location_array, $group_quantities_array);
}
}
print_r($new_array);
output:
Array
(
[audi] => Array
(
[tokyo] => 1
[barcelona] => 2
[paris] => 7
)
[ford] => Array
(
[london] => 3
[prag] => 6
)
)
<?php
$inputs = array (
"group_name_1" => "audi",
"group_locations_1" => "tokyo,barcelona,paris",
"group_quantities_at_locations_1" => "1,2,7",
"group_name_2" => "ford",
"group_locations_2" => "london,prag",
"group_quantities_at_locations_2" => "3,6"
);
$result = array();
foreach ($inputs as $key => $value) {
if (!preg_match('/group_name_([0-9]*)/', $key, $matches)) {
continue;
}
$locations = explode(',', $inputs['group_locations_' . $matches[1]]);
$quantities = explode(',', $inputs['group_quantities_at_locations_' . $matches[1]]);
$result[$value] = array_combine($locations, $quantities);
}
echo '<pre>';
var_dump($result);
echo '</pre>';
You can simply use array_walk like as
$result = [];
$chunked = array_chunk($input,3);
array_walk($chunked,function($v) use (&$result){
$result[$v[0]] = array_combine(explode(",",$v[1]),explode(",",$v[2]));
});
print_R($result);
Demo
I am trying to create an array out of three arrays in the following manner:
$file_data = array();
foreach($file_ids as $key => $id){
foreach($file_names as $name_key => $name){
foreach($file_amounts as $file_key => $cost){
$file_data[] = array("id" => $id, "filename" => $name, "amount" => $cost);
break;
}
break;
}
}
It's creating the first row only. How can I get it to properly assign the values to the $file_data array?
Thanks.
UPDATE:
As an example, I have the following for the three arrays
$file_ids[0] = 2;
$file_ids[1] = 4;
$file_name[0] = name1;
$file_name[1] = name2;
$file_amount[0] = 10;
$file_amount[1] = 9;
These arrays will always be of the same size.
What I would like to do is iterate over these arrays and end up with a final array of the form:
$final_array = (id, name, amount)
for all rows in other arrays.
These arrays will always be of the same size.
Just loop to the width of either array:
$final_array = array();
for($i = 0; $i < count($file_name); $i++)
{
$final_array[] = array($file_ids[$i],$file_name[$i],$file_amount[$i]);
}
Make use of array_map and array_combine:
$file_ids = array(2, 4);
$file_name = array('name1', 'name2');
$file_amount = array(10, 9);
$result = array_map(null, $file_ids, $file_name, $file_amount);
$keys = array('id', 'filename', 'ammount');
$result = array_map(function($el) use ($keys) {
return array_combine($keys, $el);
}, $result);
echo '<pre>'; print_r($result); echo '</pre>';
Output:
Array
(
[0] => Array
(
[id] => 2
[filename] => name1
[ammount] => 10
)
[1] => Array
(
[id] => 4
[filename] => name2
[ammount] => 9
)
)
Only iterate over one array
$file_ids = array(2,4);
$file_name = array('name1', 'name2');
$file_amount = array(10,9);
$cnt = count($file_ids);
$file_data = array();
for($i = 0; $i < $cnt; $i++){
$file_data[] = array('id' => $file_ids[$i],
'filename' => $file_name[$i],
'amount' => $file_amount[$i]);
}
var_dump($file_data);
i have arrays like this
Array(
[0] => Array(
[member_name] => hohoho
[member_type] => SUPPLIER
[interest] => Array(
[0] => HOLIDAY
[1] => MOVIES)
),
[1] => Array(
[member_name] => jajaja
[member_validity] => 13/12/2001
[interest] => Array(
[0] => SPORTS
[1] => FOODS)
)
)
how can I put the array keys and items in a separate variable? for example, i want to have something like
$keyholder[0] = member_name,member_type,interest
$keyholder[1] = member_name,member_validity,interest
$itemholder[0] = hohoho,SUPPLIER,{HOLIDAY,MOVIES}
$itemholder[1] = jajaja,13/12/2001,{SPORTS,FOODS}
Try array_keys() and array_values()
http://php.net/manual/en/function.array-keys.php
http://www.php.net/manual/en/function.array-values.php
You can cycle through an array and get the key and values like this:
foreach ($array as $key => $val)
{
echo $key." - ".$val."<br/>";
}
$keyholder=array();
$itemholder=array();
foreach($original_array as $values){
$inner_keys=array();
$inner_values=array();
foreach($values as $key=>$value){
$inner_keys[]=$key;
$inner_values[]=$value;
}
$keyholder[]=$inner_keys;
$itemholder[]=$inner_values;
}
I think this will do it:
$cnt = count($original);
$keys = array();
$items = array();
for($i = 0; $i < $cnt; $i++) {
$keys[] = array_keys($original[$i]);
$items[] = array_values($original[$i]);
}