How to change name of keys of a multidimensional array - php

I have two arrays one of them contain a new key name
$assoc = ['name', 'lastname', 'pesel'];
and second look this
$inputs = ['John', 'Don', '987987', 'Mike', 'Evans', '89779' ];
Array $assoc is the new key name, and I would like to change [0],[1] to ['name'] etc
array(2) {
['person'] =>
array(3) {
['name'] => string(4) "John"
['lastname'] => string(3) "Don"
['pesel'] => string(6) "987987"
}
['person'] =>
array(3) {
['name'] => string(4) "Mike"
['lastname'] => string(5) "Evans"
['pesel'] => string(5) "89779"
}
}
Thanks for your help

It's pretty simple:
$new_array = array();
foreach(array_chunk($inputs, 3) as $person) {
$new_array[] = array_combine($assoc, $person);
}

<?php
$assoc=Array("name", "lastname", "pesel");
$inputs=Array('John', 'Don', '987987', 'Mike', 'Evans', '89779' );
$resultant_array=Array();
for($i=0; $i<count($inputs); $i+=count($assoc)){
//echo $i."\n\n";
for($j=0; $j<count($assoc); $j++){
$b2g[$assoc[$j]]=$inputs[$i+$j];
}
$resultant_array[]=$b2g;
}
print_r($resultant_array);
It is a more lengthy and general purpose use.. I actually have used much recurssions..

Related

Including variables in keys and values in PHP

Is there any way to shorten this array
array = [ 'student1' => 'id1', 'student2' => 'id2',];
to something like this?
array = ['student' . $n => 'id' . $n];
I will appreciate if you give me words to search!
Edit:
Sorry for the poor explanation. I wanted to do something like this:
$array = ['student'.$n => 'id'.$n];
echo($array['student1']); //id1
Loop the number of students you need and build the array with array_merge.
$students = 10;
$arr = [];
for($i = 1; $i<=$students; $i++){
$arr = array_merge($arr, ['student' . $i => 'id' . $i]);
}
var_dump($arr);
output:
array(10) {
["student1"]=>
string(3) "id1"
["student2"]=>
string(3) "id2"
["student3"]=>
string(3) "id3"
["student4"]=>
string(3) "id4"
["student5"]=>
string(3) "id5"
["student6"]=>
string(3) "id6"
["student7"]=>
string(3) "id7"
["student8"]=>
string(3) "id8"
["student9"]=>
string(3) "id9"
["student10"]=>
string(4) "id10"
}

How can I flatten a Multidimensional array into a string?

Ive researched this but im coming up blank, Im generating an array of tests from a database like so:
$descriptions = array();
foreach ($tests as $value) {
array_push($descriptions, ['name' => $value['name']]);
}
I'm getting the desired out put but i'm getting a Multidimensional array of an array with '[64]' arrays inside '$descriptions', I need to convert this array so I get the following output:
'name' => $value1, 'name' => $value2, etc etc for all results,
I've tried implode, array_merge etc but the closest I've got is a flat array with only my last test: [name] => Zika can anyone point me in the right direction? cheers
You can't have duplicate array keys. But you can pass an array in like so:
<?php
$descriptions = array();
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions[] = array('name' => $value);
}
var_dump($descriptions);
Which gives you :
array(6) { [0]=> array(1) { ["name"]=> string(4) "Zika" } [1]=> array(1) { ["name"]=> string(4) "SARS" } [2]=> array(1) { ["name"]=> string(4) "AIDS" } [3]=> array(1) { ["name"]=> string(15) "Mad Cow Disease" } [4]=> array(1) { ["name"]=> string(8) "Bird Flu" } [5]=> array(1) { ["name"]=> string(16) "Zombie Infection" } }
So you could foreach ($descriptions as $desc) and echo $desc['name']';
Have a look here: https://3v4l.org/pWSC6
If you just want a string, try this:
<?php
$descriptions = '';
$tests = array(
'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',
);
foreach ($tests as $value) {
$descriptions .= 'name => '.$value.', ';
}
$descriptions = substr($descriptions, 0, -2); // lose the last comma
echo $descriptions;
Which will output:
name => Zika, name => SARS, name => AIDS, name => Mad Cow Disease, name => Bird Flu, name => Zombie Infection
See it here https://3v4l.org/OFGF4

Combine multiple form array into 1 array

["trnx_date"]=>
array(2) {
[0]=>
string(10) "2017-01-10"
[1]=>
string(10) "2017-01-10"
}
["curr_from"]=>
array(2) {
[0]=>
string(3) "USD"
[1]=>
string(3) "PHP"
}
["curr_from_amt"]=>
array(2) {
[0]=>
string(8) "4,000.00"
[1]=>
string(8) "3,000.00"
}
["curr_to"]=>
array(2) {
[0]=>
string(3) "GBP"
[1]=>
string(3) "SAR"
}
["curr_to_amt"]=>
array(2) {
[0]=>
string(8) "3,000.00"
[1]=>
string(8) "2,000.00"
}
["amount"]=>
array(2) {
[0]=>
string(8) "7,000.00"
[1]=>
string(8) "5,000.00"
}
I have the above array which was being submitted. This input was in sets of multiple field which was generated by dynamic table row. How can I group this into 1 (one) array so that I could save in the database? Like this:
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "USD",
'curr_from_amt' => "4,000.00",
'curr_to' => "GBP",
'curr_to_amt' => "3,000.00",
'amount' => "7,000.00"
),
[cust_row] => array(
'tranx_date' => "2017-01-10",
'curr_from' => "PHP",
'curr_from_amt' => "3,000.00",
'curr_to' => "SAR",
'curr_to_amt' => "2,000.00",
'amount' => "5,000.00"
),
All of the above we being populated like this:
$trnx_date = $this->input->post('trnx_date');
$curr_from = $this->input->post('curr_from');
$curr_from_amt = $this->input->post('curr_from_amt');
$curr_to = $this->input->post('curr_to');
$curr_to_amt = $this->input->post('curr_to_amt');
$amount = $this->input->post('amount');
Assuming all the sub-arrays have the same length, you can use a simple for loop that iterates over the index of one of them, and use that to access each of the sub-arrays at that index. Then combine all of them into the associative array for each customer.
$result = array();
$keys = array_keys($array);
$len = count($array[$keys[0]]); // Get the length of one of the sub-arrays
for ($i = 0; $i < $len; $i++) {
$new = array();
foreach ($keys as $k) {
$new[$k] = $array[$k][$i];
}
$result[] = $new;
}
$arr = array(
'trnx_date' => array('2017-01-10', '2017-01-10'),
'curr_from' => array('USD', 'PHP'),
'curr_from_amt' => array('4,000.00', '3,000.00'),
'curr_to' => array('GBP', 'SAR'),
'curr_to_amt' => array('3,000.00', '2,000.00'),
'amount' => array('7,000.00', '5,000.00')
);
$arr_out = array();
$arr_keys = array_keys($arr);
for($i = 0; $i < count($arr[$arr_keys[0]]); $i++) {
$new_arr = array();
foreach($arr_keys as $key => $value) {
$new_arr[$value] = $arr[$value][$i];
}
$arr_out[] = $new_arr;
}
var_dump($arr_out);
Hope it helps!
How about this?
// assume $arr is your original data array
$keys = array_keys($arr);
$result = array();
foreach($keys as $key) {
$vals = $arr[$key];
foreach($vals as $i =>$val) {
if (!is_array($result[$i]) {
$result[$i] = array();
}
$result[$i][$key] = $val;
}
}
var_dump($result);
EDIT: added array check for $result[$i]

convert array with objects to one associative array without foreach

I have an array like(result of json_decode):
array(2) {
[0]=>
object(stdClass)#1 (3) {
["key"]=>
string(6) "sample"
["startYear"]=>
string(4) "2000"
["endYear"]=>
string(4) "2015"
}
[1]=>
object(stdClass)#2 (3) {
["key"]=>
string(13) "second_sample"
["startYear"]=>
string(4) "1986"
["endYear"]=>
string(4) "1991"
}
}
I want to convert it to array like:
array(2) {
["sample"]=>
array(2) {
["startYear"]=>
string(4) "2000"
["endYear"]=>
string(4) "2015"
}
["second_sample"]=>
array(2) {
["startYear"]=>
string(4) "1986"
["endYear"]=>
string(4) "1991"
}
}
Is there beauty way to do this (cureently I'm using foreach, but I'm not sure it is a best solution).
Added a code example:
<?php
$str='[{"key":"sample","startYear":"2000","endYear":"2015"},{"key":"second_sample","startYear":"1986","endYear":"1991"}]';
$arr=json_decode($str);
var_dump($arr);
$newArr=array();
foreach ($arr as $value){
$value=(array)$value;
$newArr[array_shift($value)]=$value;
}
var_dump($newArr);
You can use array_reduce
$myArray = array_reduce($initialArray, function ($result, $item) {
$item = (array) $item;
$key = $item['key'];
unset($item['key']);
$result[$key] = $item;
return $result;
}, array());
You can create the desired output without making any iterated function calls by using a technique called "array destructuring" (which is a functionless version of list()). Demo
Language Construct Style:
$result = [];
foreach ($array as $object) {
[
'key' => $key,
'startYear' => $result[$key]['startYear'],
'endYear' => $result[$key]['endYear']
] = (array)$object;
}
var_export($result);
Functional Style:
var_export(
array_reduce(
$array,
function($result, $object) {
[
'key' => $key,
'startYear' => $result[$key]['startYear'],
'endYear' => $result[$key]['endYear']
] = (array)$object;
return $result;
},
[]
)
);
Both will output:
array (
'sample' =>
array (
'startYear' => '2000',
'endYear' => '2015',
),
'second_sample' =>
array (
'startYear' => '1985',
'endYear' => '1991',
),
)
Simply you can use array_map like as
$result = array_map('get_object_vars',$your_array);
Edited:
As after checking your code that you've added an example over here there's no need to use an extra functions or loop to convert your array of objects into associative array instead you simply need to pass second parameter true within json_decode function like as
$arr = json_decode($json,true);
Demo
An alternative to array_reduce and other provided solutions could be:
$list = array_combine(
array_column($list, 'key'),
array_map(fn ($item) => (array) $item, array_values($list))
);
Or:
$list = array_combine(
array_column($list, 'key'),
array_map('get_object_vars', $list)
);

Reading PHP array using key value

I have an array that I'm creating inside my PHP script, the var_dump function gives me this value :var_dump($arrayOfValues);
array(3) {
[0]=> array(2) {
[0]=> string(12) "BusinessName"
[1]=> string(13) "ITCompany"
}
[1]=> array(2) {
[0]=> string(7) "Address"
[1]=> string(58) "29 xxxxxx,Canada"
}
[2]=> array(2) {
[0]=> string(20) "PrimaryBusinessPhone"
[1]=> string(14) "(444) 111-1111"
}
[3]=> array(2) {
[0]=> string(13) "BusinessEmail"
[1]=> string(24) "xx#example.com"
}
}
I would like to access to the value of the "BusinessName" using key and not index so if I put : echo $arrayOfValue[0][1]; it gives me the BusinessName that is ITCompany but if I put
: echo $arrayOfValue['BusinessName'][1]; it gives nothing so how can I fix that please?
The array is initialized $arrayOfValue = array(); and then populated dynamically inside a for loop like that
$arrayOfValue[] = array($Label, $Value);
your array has this kind of data
$arrayOfPostsValue[] = array("BusinessName","ITCompany");
$arrayOfPostsValue[] = array("Address","29 xxxxxx,Canada");
$arrayOfPostsValue[] = array("PrimaryBusinessPhone","(444) 111-1111");
$arrayOfPostsValue[] = array("BusinessEmail","xx#example.com");
there is no array key in data So, you have to recreate your desire array
$newArrayOfPostsValue = array();
foreach ( $arrayOfPostsValue as $value ){
$newArrayOfPostsValue[$value[0]] = $value[1];
}
print_r($newArrayOfPostsValue);
and here is output
Array
(
[BusinessName] => ITCompany
[Address] => 29 xxxxxx,Canada
[PrimaryBusinessPhone] => (444) 111-1111
[BusinessEmail] => xx#example.com
)
As mentioned in the comment, change the structure of the array, it will be much easier to handle
$my_array = array(
array('Business Name' => 'It Company'),
array('Address' => 'My address')
);
Looking at the content of your array, I will restructure it as
$my_improved_array = array(
'BusinessName' => 'It Company',
'Address' => 'My Address',
);
This is how you can access,
echo $my_array[0]['BusinessName'] //prints 'It Company'
echo $my_array[1]['Address'] //prints 'My Address'
echo $my_improved_array['BusinessName'] // prints 'It Company'
Try like this and save array as key value pairs and then access the key:
foreach($arrayOfValues as $a)
$arr[$a[0]] = $a[1];
echo $arr['BusinessName'];
While creating that array build it with index as BusinessName
array (
0 => array(
'BusinessName'=> "ITCompany"
)
1 => array(1) (
'Address'=> "29 xxxxxx,Canada"
)
)
etc..
PHP Array example
$array = array();
$array['BusinessName'] = 'ITCompany';
$array['Address'] = '29 xxxxxx,Canada';
And so on... Now you can echo values with
echo $array['BusinessName'];
Also this works
$array = array('BusinessName' => 'ITCompany', 'Address' => '29 xxxxxx,Canada');
First of all, how are you building this array ? Maybe you can directly make a workable array.
Anyway, you can do something like this :
$oldArray = Array(
Array("BusinessName", "ITCompany"),
Array("Address", "29 xxxxxx,Canada"),
Array("PrimaryBusinessPhone", "(444) 111-1111"),
Array("BusinessEmail", "xx#example.com")
);
$newArray = Array();
foreach($oldArray as value) {
$newValue[$value[0]] = $value[1];
}
/* Now, it's equal to
$newArray = Array(
"BusinessName" => "ITCompany",
"Address" => "29 xxxxxx,Canada",
"PrimaryBusinessPhone" => "(444) 111-1111",
"BusinessEmail" => "xx#example.com"
);
*/

Categories