This question already has answers here:
how to change index of an array in php [duplicate]
(3 answers)
Closed 4 years ago.
Good day everyone,
I was tasked to change index in arrays.
here is my code:
$file = Storage::get('upload/test.txt');
$lines = explode('\n', $file);
$array = array_map(function($line) {
return explode(',', $line);
}, $lines);
print_r($array);
output is:
Array
(
[0] => Array
(
[0] => john
[1] => male
[2] => 20
[3] => 200
[4] => 174
)
[1] => Array
(
[0] => joe
[1] => male
[2] => 24
[3] => 157
[4] => 166
)
[2] => Array
(
[0] => bea
[1] => female
[2] => 18
[3] => 153
[4] => 160
)
[3] => Array
(
[0] => edd
[1] => male
[2] => 30
[3] => 180
[4] => 180
)
)
what i need to happen is:
Array
(
[0] => Array
(
[name] => john
[sex] => male
[age] => 20
[height] => 200
[weight] => 174
)
[1] => Array
(
[name] => joe
[sex] => male
[age] => 24
[height] => 157
[weight] => 166
)
[2] => Array
(
[name] => bea
[sex] => female
[age] => 18
[height] => 153
[weight] => 160
)
[3] => Array
(
[name] => edd
[sex] => male
[age] => 30
[height] => 180
[weight] => 180
)
)
thanks in advance! :)
You want an associative array.
$newArray = []; // create a new empty array to store your associative arrays.
// Loop through each element in array.
foreach($array as $aPerson) {
// map each element in array into an associative array.
$person = [
"name" => $aPerson[0],
"sex" => $aPerson[1],
"age" => $aPerson[2],
"height" => $aPerson[3],
"weight" => $aPerson[4]
];
// Add your associative array to your new re-indexed array.
array_push($newArray, $person);
}
I hope this helps.
The following should print the array in the format you want.
print_r($newArray);
Simple, Like this:
$arr = [
['joe','male',24,157,166]
];
#mind the & pass by refrence
foreach($arr as &$item){
$item = array_combine(['name','sex','age','height','weight'],$item);
}
print_r($arr);
Output
Array
(
[0] => Array
(
[name] => joe
[sex] => male
[age] => 24
[height] => 157
[weight] => 166
)
)
Sandbox
Note array_combine will blow up if the 2 arrays are not the same size.
You can do this too (84 bytes)
$arr = [['joe','male',24,157,166]];
$headers = ['name','sex','age','height','weight'];
$arr = array_map(function($item)use($headers){return array_combine($headers,$item);},$arr);
print_r($arr);
Same output
Sandbox
A possible solution will be to create a new array, loop through the current one and add the indexes:
$new_array = array();
foreach ($array as $element) {
$new_array[] = array(
'name' => $element[0],
'sex' => $element[1],
'age' => $element[2],
'height' => $element[3],
'weight' => $element[4]
);
$i++;
}
Here is how I would do what you're trying to achieve
<?php
$fp = #fopen('upload/test.txt', 'r'); $props = ['name', 'sex', 'age', 'height', 'weight']; $r = [];
if($fp) {
while(($line = fgets($fp)) !== false) {
$x = explode(',', $line); $a = [];
foreach($props as $k => $v){
$a[$v] = $x[$k];
}
$r[] = $a;
}
fclose($fp);
}
print_r($r);
?>
Related
I'm trying to create a function that will sort this form of array (originally with dynamic values):
Array
(
[0] => product_cat-24
[1] => style_cat-97
[2] => style_cat-98
[3] => stone_count_cat-110
[4] => style_cat-100
[5] => style_cat-104
[6] => stone_count_cat-109
[7] => stone_count_cat-111
)
So it will look like this:
Array(
'product_cat' => array( 24 ),
'style_cat' => array( 97, 98, 100, 104 ),
'stone_count_cat' => array( 110, 109, 111 )
);
The only thing that matters is to assign the number to its proper key.
Looking for the must elegant way to achieve that.
Thanks! :)
Simply try like this with explode() and list() of PHP.
<?php
$array = array
(
'product_cat-24',
'style_cat-97',
'style_cat-98',
'stone_count_cat-110',
'style_cat-100',
'style_cat-104',
'stone_count_cat-109',
'stone_count_cat-111'
);
$new = array();
foreach($array as $val) {
list($key, $value) = explode('-', $val);
$new[$key][] = $value;
}
print '<pre>';
print_r($new);
print '<pre>';
?>
OUTPUT:
Array
(
[product_cat] => Array
(
[0] => 24
)
[style_cat] => Array
(
[0] => 97
[1] => 98
[2] => 100
[3] => 104
)
[stone_count_cat] => Array
(
[0] => 110
[1] => 109
[2] => 111
)
)
DEMO: https://eval.in/980195
You can also do like this:
$new = array();
foreach( $array as $val) {
$tmp = explode('-', $val);
$new[$tmp[0]][] = $tmp[1];
}
I have a page where it prints out this value:
"Firstname","Ana","George","Wilson"
"Lastname","Smith","Spencer","Carey"
"Age","18","20","22"
I get the values of these using file_get_contents and str_getcsv.
$array= str_getcsv($test);
The Array results that I get is this
Array ( [0] =>
"Firstname"
[1] => 'Ana'
[2] => 'George'
[3] => 'Wilson'
"Lastname"
[4] => 'Smith'
[5] => 'Spencer'
[6] => 'Carey'
"Age"
[7] => 18
[8] => 20
[9] => 22
))
Is there anyway I can change the Array format into this?
Array
(
[0] => Array
(
[0] => 'Ana'
[1] => 'George'
[2] => 'Wilson'
)
[1] => Array
(
[0] => 'Smith'
[1] => 'Spencer'
[2] => 'Carey'
)
[2] => Array
(
[0] => 18
[1] => 20
[2] => 22
)
)
Instead of using file_get_contents() and str_getcsv(), i will recomend you to use file()
Do like below:-
<?php
$test = file('test.txt'); // you can add your file url here
echo "<pre/>";print_r($test);// initial array
foreach($test as &$te){
$new_array = explode(',',$te);
unset($new_array[0]);
$te = array_values($new_array);
}
echo "<pre/>";print_r($test); // modified and desired array
To change the given array to a specified format:
$array = ['Firstname' => ['Ana', 'George', 'Wilson'], 'Lastname' => ['Smith', 'Spencer', 'Carey'], 'Age' => [18, 20, 22]];
$new_array = [];
foreach ($array as $key => $value) {
$new_array[] = $value;
}
print_r($new_array);
Array
(
[Firstname] => Array
(
[0] => Ana
[1] => George
[2] => Wilson
)
[Lastname] => Array
(
[0] => Smith
[1] => Spencer
[2] => Carey
)
[Age] => Array
(
[0] => 18
[1] => 20
[2] => 22
)
)
Try This bro i hope i can help:
$array = array(0=> array(
'firstname' => array(1 => 'Ana', 2 => 'George', 3=>'Wilson'),
'lastname' => array(4=>'Smith', 5=>'Spencer', 6=> 'Carey'),
'age' => array(7=>18,8=>20,9=>22)
));
$newArray = array();
echo "<pre/>";print_r($array);
foreach($array as $key=>$new){
foreach($new as $k=>$d){
$newArray[] = array_values($d);
}
}
echo "</br>New Array Format: </br>";
echo "<pre/>";print_r($newArray);
I have an array structure like this and wanted to Re-arrange it to the one below. Any suggestions for a faster/simple fix? I already did the addition of the dates. Thanks! :)
Input:
Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
[company_name] => Company_A
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
[company_name] => Company_A
)
[2] => Array
(
[user_id] => 25
[display_name] => Hulk
[company_name] => Company_B
)
[3] => Array
(
[user_id] => 50
[display_name] => Bob
[company_name] => Company_B
)
)
Output:
Array
(
[Company_A] => Array
(
[company_total_hours] => 20h 45m
[employees] => Array
(
[0] => Array
(
[user_id] => 255
[display_name] => Mark
)
[1] => Array
(
[user_id] => 150
[display_name] => Paul
)
)
)
[Company_B] => Array
(
[company_total_hours] => 7h 30m
[employees] => Array
(
[0] => Array
(
[user_id] => 25
[display_name] => Hulk
)
[1] => Array
(
[user_id] => 50
[display_name] => Bob
)
)
)
)
My Attempts:
<?php
$company_names = array();
foreach ($records as $k => $v) {
$company_names[] = $v->company_name;
}
$company_names = array_unique($company_names);
// hard coded testing
if (count($company_names) > 0) {
foreach($company_names as $k2 => $v2) {
$final_array[$v2]['company_total_hours'] = rand(1, 20);
$final_array[$v2]['employees'] = array(
array('user_id' => '255', 'display_name' => 'Mark'),
array('user_id' => '150', 'display_name' => 'Paul')
);
}
}
// on-going testing right now here....
I don't see where you derive your hours from so I left that out.
$i = 0;
foreach($vals as $keys => $arrays) {
if(!isset($new[$arrays['company_name']]))
$i = 0;
$new[$arrays['company_name']]['employees'][$i]['display_name'] = $arrays['display_name'];
$new[$arrays['company_name']]['employees'][$i]['user_id'] = $arrays['user_id'];
$i++;
}
Gives you:
Array
(
[Company_A] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Mark
[user_id] => 255
)
[1] => Array
(
[display_name] => Paul
[user_id] => 150
)
)
)
[Company_B] => Array
(
[employees] => Array
(
[0] => Array
(
[display_name] => Hulk
[user_id] => 25
)
[1] => Array
(
[display_name] => Bob
[user_id] => 50
)
)
)
)
foreach($arr as $v)
{
if(!$arr2[$v['company_name']]['employees'])
$arr2[$v['company_name']]['employees'] = array();
if(!$arr2[$v['company_name']]['company_total_hours'])
$arr2[$v['company_name']]['company_total_hours'] = '2h';//addional value
$arr2[$v['company_name']]['employees'][] = array('user_id'=>$v['user_id'],
'display_name'=>$v['display_name']
);
}
I have created a function which does the same thing as the answer given by #Rasclatt.
function groupByKeyValue($array, $oldKeyName, $newKeyName){
$newArray = array();
foreach($array as $key=>$value){
if(isset($newArray[$value[$oldKeyName]][$newKeyName])){
$newArray[$value[$oldKeyName]][$newKeyName][] = array('user_id'=> $value['user_id'], 'display_name' => $value['display_name']);
}else{
$newArray[$value[$oldKeyName]] = array($newKeyName => array(array('user_id'=> $value['user_id'], 'display_name' => $value['display_name'])));
}
}
return $newArray;
}
//usage
$newArray = groupByKeyValue($array, 'company_name', 'employees');
You can add a third parameter to send the keys for the array values which needs to be used in the new array for 'employees'. Please check this link for the working of the function http://goo.gl/I6Of5y
I have an array look like this via CSV:
Array
(
[0] => Array
(
[0] => Agent Name
[1] => Total Calls
[2] => Customer Services
[3] => Voicemail
)
[1] => Array
(
[0] => Paul
[1] => 53
[2] => 0
[3] => 0
)
[2] => Array
(
[0] => Sarah
[1] => 51
[2] => 0
[3] => 0
)
)
I would like to tidy an array to make it to more readable and easy to use.
I want an array to look something like this:
Array
(
[Paul] => Array
(
[Agent Name] => Paul
[Total Calls] => 53
[Customer Services ] => 30
[Voicemail ] => 0
)
[Sarah] => Array
(
[Agent Name] => Sarah
[Total Calls] => 51
[Customer Services ] => 0
[Voicemail ] => 0
)
)
I have came up with this solution and it work:
$fields = $report[0];
array_shift($report);
$data = array();
foreach($report as $row) {
$data[$row[0]] = array();
foreach($row as $k => $val) {
$data[$row[0]][$fields[$k]] = $val;
}
}
return $data;
Is there a better shorter way doing this?
Try
$result =array();
for($i=1;$i<count($arr);$i++){
$result[$arr[$i][0]] = array_combine(array_values($arr[0]),$arr[$i]);
}
See demo here
You could perhaps do it like this:
$f = array_shift($report);
$a = array_combine(array_column($t = array_map(function ($r) use ($f)
{
return array_combine($f, $r);
}
, $report), 'Agent Name'), $t);
I have a new PHP problem. I have 2 arrays, and I want a third array which is a combination of the first 2. The first array, $arr1, is something like this:
Array (
[0] => name [1] => age
)
The second array, $arr2, is something like this:
Array (
[0] => Array( [0] => Dave [1] => 20 )
[1] => Array( [0] => Steve [1] => 25 )
[2] => Array( [0] => Ace [1] => 23 )
)
And my idea is to create a new array, called $arr3, which should like this:
Array (
[0] => Array( [name] => Dave [age] => 20 )
[1] => Array( [name] => Steve [age] => 25 )
[2] => Array( [name] => Ace [age] => 23 )
)
Can anyone tell me how to do this?
$arr3 = array();
foreach ($arr2 as $person) {
$arr3[] = array_combine($arr1, $person);
}
foreach($arr2 as $subArray){
foreach($subArray as $i=>$val){
$arr3[$arr1[$i]] = $val;
}
}