This question already has answers here:
What's the most straightforward way in PHP to create an associative array from two parallel indexed arrays?
(2 answers)
Turn indexed array to associative array [duplicate]
(2 answers)
Closed last month.
I have two array values:
$values = ["Phillip", "Phil"];
In my set() method, I want to return an array object that first has a defined name key and second nickname key, like:
array(2) {
"name" => "Phillip"
"nickname" => "Phil"
}
Is there a better way to do it? I am new at PHP, though.
function set(?array $values)
{
$items = [];
foreach ($values as &$item) {
$item['name'] = $items;
$item['nickname'] = $items;
}
}
Like this
<?php
$values = ["Phillip", "Phil"];
function set(array $values): array
{
return [ "name" => $values[0], "nickname" => $values[1] ];
}
var_dump(set($values));
Result
array(2) {
["name"]=>
string(7) "Phillip"
["nickname"]=>
string(4) "Phil"
}
Related
This question already has answers here:
How to filter an associative array comparing keys with values in an indexed array?
(12 answers)
Closed 9 months ago.
0 => array[
"id" => "94e568e2-e5ef-4565-b9d1"
"code" => "8899014500001"
"name" => "John"
"age" => "24" ]
I'm trying to convert an array of users into a CSV file. And i set the array of the key that I want to export.
$fields = ['id', 'name'];
How can I fputcsv in foreach loop return only user id and name from $fields array ?
foreach ($user as $item) {
fputcsv($output, $item);
}
Make an array containing only the fields you want using the $fields array to decide what to place in the output
$fields = ['id', 'name'];
foreach ($users as $user) {
$out = [];
foreach ( $fields as $field){
$out[$field] = $user[$field];
}
fputcsv($output, $out);
}
This question already has answers here:
Flip associative array and store new values in subarrays to prevent losing duplicated values
(3 answers)
Closed 1 year ago.
I'm trying to flip array but it missed value from the key with the same name.
What do I have to use, to add couple values to key which occur multiple times in array?
For example, for
[
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
]
the groupByOwners function should return
[
"Randy" => ["Input.txt", "Output.txt"],
"Stan" => ["Code.py"]
]
The current code:
class FileOwners
{
static $files;
public static function groupByOwners($files)
{
$flip = array_flip($files);
print_r($flip);
}
}
$files = array
(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
);
My function return Array ( [Randy] => Output.txt [Stan] => Code.py ) NULL.
So value "Input.txt" is missing. It has to be the same key for both values, so how can I put "Input.txt" with "Output.txt" in array for key [Randy]?
You will have to loop it yourself and build a new array:
$files = array(
"Input.txt" => "Randy",
"Code.py" => "Stan",
"Output.txt" => "Randy"
);
$new_files = array();
foreach($files as $k=>$v)
{
$new_files[$v][] = $k;
}
print_r($new_files);
A somewhat quick and a little hacky solution:
php > $files = array
php > (
php ( "Input.txt" => "Randy",
php ( "Code.py" => "Stan",
php ( "Output.txt" => "Randy"
php ( );
php > var_dump(array_reduce(array_keys($files), function($p, $c) use (&$files) { $p[$files[$c]] = $p[$files[$c]] ?? []; $p[$files[$c]][] = $c; return $p; }, []));
array(2) {
["Randy"]=>
array(2) {
[0]=>
string(9) "Input.txt"
[1]=>
string(10) "Output.txt"
}
["Stan"]=>
array(1) {
[0]=>
string(7) "Code.py"
}
}
NB: The use of '??' requires PHP 7.0.
Just to pull the important part out of the one-liner and make it at least slightly more readable:
array_reduce(array_keys($files), function($p, $c) uses (&$files) {
$p[$files[$c]] = $p[$files[$c]] ?? [];
$p[$files[$c]][] = $c;
}, []);
You could just as easily use the if(isset(...)) logic to ensure the array element in $p exists.
This question already has answers here:
Turning multidimensional array into one-dimensional array [duplicate]
(11 answers)
Closed 4 years ago.
I need to flatten an array while making sure that there are no duplicate keys.
For instance let's say I have this:
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
I need a flattened array that looks like this:
$arr = array(
'donuts name' => 'lionel ritchie',
'donuts animal' => 'manatee',
);
It needs to work even if we have more than 1 parent keys.
I have the following code, but I am not sure I can work with this.
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)) as $k=>$v){
$array1c[$k] = $v;
}
It's very simple to do, just make it like this:
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
// Will loop 'donuts' and other items that you can insert in the $foo array.
foreach($foo as $findex => $child) {
// Remove item 'donuts' from array, it will get the numeric key of current element by using array_search and array_keys
array_splice($foo, array_search($findex, array_keys($foo)), 1);
foreach($child as $index => $value) {
// Adds an array element for every child
$foo[$findex.' '.$index] = $value;
}
}
Result of var_dump($foo); will be:
array(2) {
["donuts name"]=>
string(14) "lionel ritchie"
["donuts animal"]=>
string(7) "manatee"
}
Just try :)
I have an array from json_decode. And i want to reformat it.
this is my array format.
["Schedule"]=>array(1) {
["Origin"]=>
string(3) "LAX"
["Destination"]=>
string(2) "CGK"
["DateMarket"]=>
array(2) {
["DepartDate"]=>
string(19) "2015-02-01T00:00:00"
["Journeys"]=>
array(6) {
[0]=>
array(6) {
[0]=>
string(2) "3210"
[1]=>
string(14) "Plane Name"
[2]=>
string(8) "20150201"
[3]=>
string(8) "20150201"
[4]=>
string(4) "0815"
[5]=>
string(4) "1524"
}
}
}
And i want change the indexed array to associative with foreach function.
And here is my PHP code
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value->Name= $value[1];
}
But i got an error "Attempt to assign property of non-object on line xXx..
My Question is, how to insert a new associative array to indexed array like the example that i've provide.
UPDATE : I've tried this solution
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name']=$value[1];
}
But my array format still the same, no error.
In this line:
$value->Name= $value[1];
You expect $value to be both object ($value->Name) and array ($value[1]).
Change it to something like:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$response->Schedule['DateMarket']['Journeys'][$key]['Name'] = $value[1];
}
Or even better, without foreach:
$keys = array(
0 => 'Id',
1 => 'Name',
2 => 'DateStart',
3 => 'DateEnd',
4 => 'HourStart',
5 => 'HourEnd',
);
$values = $response->Schedule['DateMarket']['Journeys'];
$response->Schedule['DateMarket']['Journeys'] = array_combine( $keys , $values );
Array_combine makes an array using keys from one input and alues from the other.
Docs: http://php.net/manual/en/function.array-combine.php
Try this:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name'] = $value[1];
}
You want to create new array index, but try to create new object.
foreach ($response->Schedule['DateMarket']['Journeys'] as $key => $value) {
$value['Name'] = $value[1];
}
I am trying to convert the associative array to an array of objects.
$assoc = array (
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
)
Here Is the code I have so far:
class Assoc {
public function setObject($assoc) {
$this->assoc[] = new Obj($assoc);
}
}
class Obj {
public function __construct($item) {
foreach ( $item as $property=>$value ) {
$this->{$property} = $value;
}
}
}
$test = New Assoc();
$test->setObject($assoc);
This code will work for a single array but not an array of arrays. If you could help with what I believe to be the loop in the setObject function.
Convert the associative array to an array of objects:
$output = array_map(function($element) {
return (object) $element;
}, $assoc);
Simple enough.
EDIT: If you need to make objects of a specific class:
$output = array_map(function($element) use ($classType) {
return new $classType($element);
}, $assoc);
You can generalize it into just about anything, really.
EDIT for specific object:
To adhere to your existing style as close as possible without messing with array_map voodoo:
class Assoc {
public function setObject($assoc) {
foreach ($assoc as $arr) {
$this->assoc[] = new Obj($arr);
}
}
}
class Obj {
public function __construct($item) {
foreach ( $item as $property=>$value ) {
$this->{$property} = $value;
}
}
}
$test = New Assoc();
$test->setObject($assoc);
Original:
If you just need generic conversion, and not into specific custom objects (not exactly clear in your post?) you can try this:
$new_array = array();
foreach ($assoc as $to_obj)
{
$new_array[] = (object)$to_obj;
}
// Print results
var_dump($new_array);
outputs:
array(2) {
[0]=>
object(stdClass)#1 (2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}
[1]=>
object(stdClass)#2 (2) {
["prop1"]=>
string(4) "val1"
["prop2"]=>
string(4) "val2"
}
}
$len = count($assoc);
for($i=0;$i<$len; $i++){
$assoc[$i] = (Object)$assoc[$i];
}
You have an indexed array of associative arrays. If you convert it to json then back to an iterable state with the default behavior of json_decode(), the top level (indexed array) will be cast as array-type while the subarrays will become object-type.
Note that this will conversion will permeate all the way through subsequent levels of data (in case researchers might have deeper data structures). Effectively, indexed arrays remain indexed arrays and associative arrays become objects.
This is such a basic call that I am not sure that creating a wrapper for it is necessary.
Code: (Demo)
$assoc = array (
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
array(
'prop1'=>'val1',
'prop2'=>'val2',
),
);
var_export(
json_decode(json_encode($assoc))
);
Output:
array (
0 =>
(object) array(
'prop1' => 'val1',
'prop2' => 'val2',
),
1 =>
(object) array(
'prop1' => 'val1',
'prop2' => 'val2',
),
)