The question is simple, I want to create the array below dynamically, but the code I got now only outputs the last row. Is there anybody who knows what is wrong with my dynamically array creation?
$workingArray = [];
$workingArray =
[
0 =>
[
'id' => 1,
'name' => 'Name1',
],
1 =>
[
'id' => 2,
'name' => 'Name2',
]
];
echo json_encode($workingArray);
/* My not working array */
$i = 0;
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
$i++;
}
}
echo json_encode($dynamicArray);
You dont need to have the $i stuff that is adding another level to your array that you dont want.
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray[] = ['id' => $key, 'name' => $value['options'];
}
}
echo json_encode($dynamicArray);
You are creating a new dynamic array at each iteration:
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
Instead, declare $dynamicArray = []; above the foreach, and then use:
array_push($dynamicArray, [ 'id' => $key, 'name' => $value['options']);
inside the array.
Related
Basically I have an associative array from the database like below,
persons = [
[id=>1, name=>adam, hobbyId=>x, hobbyName=> swim],
[id=>2, name=>brian, hobbyId=>y, hobbyName=> read],
[id=>1, name=>adam, hobbyId=>z, hobbyName=> sing]
]
I want to convert it to a new style like JSON object, something like this,
new_persons = [
[id=>1, name=>adam, hobbies => [[hobbyId=>x, hobbyName=> swim],[hobbyId=>z,
hobbyName=> sing]],
[id=>2, name=>brian, hobbies => [[hobbyId=>y, hobbyName=>read]]
]
What I have tried is,
$new_persons = array();
if (count($persons) > 0) {
foreach ($persons as $item) {
$detail = array(
'id' => $item['id'],
'name' => $item['name'],
'hobbies' => [['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]]
);
if (in_array($item['id'], $newArray)) {
array_push($newArray['hobbies'], ['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]);
} else {
array_push($newArray, $detail);
}
}
}
But it doesn't meet my requirements, What is wrong with my code?
$t2 = [];
foreach ($t as $item) {
if (!isset($t2[$item['id']])) {
$t2[$item['id']] = [
'id' => $item['id'],
'name' => $item['name'],
];
}
$t2[$item['id']]['hobbies'][] = [
'hobbyId' => $item['hobbyId'],
'hobbyName' => $item['hobbyName'],
];
}
I usually use Eloquent so transposing the data is much easier. However i'm struggling to this in vanilla PHP.
I have tried array_map(null, ...$array) however get an error due to it not being an array.
I have got the following keyed array:
[
'email' => [
"william.pool#gmail.com",
"martynleeball#gmail.com"
],
'lastName' => [
'Pool',
'Ball'
],
'firstName' => [
'William',
'Martyn'
],
'id' => [
'j8zwyk',
'1'
]
]
I need to convert this to the following format:
[
0 => [
'email' => "william.pool#gmail.com",
'lastName' => 'Pool',
'firstName' => 'William',
'id' => 'j8zwyk'
],
1 => [
'email' => "martynleeball#gmail.com",
'lastName' => 'Ball',
'firstName' => 'Martyn',
'id' => '1'
]
]
Create new array with length 2 and loop through origin array. In loop insert relevant item into new array.
So if your array has only 2 item per key use
$newArr = [];
foreach($arr as $key=>$item){
$newArr[0][$key] = $item[0];
$newArr[1][$key] = $item[1];
}
But if it has unknown item use
$newArr = [];
foreach($arr as $key=>$item){
foreach($item as $key2=>$item2)
$newArr[$key2][$key] = $item2;
}
Check result in demo
$newArray = [];
foreach ($array as $key => $value) {
for ($i = 0; $i < count($value); $i++) {
$newArray[$i][$key] = $value[$i];
}
}
This question already has answers here:
Group subarrays by one column, make comma-separated values from other column within groups
(2 answers)
Closed last month.
I have a two dimensional array which needs to be restructured. Rows must be grouped by date values, and within each group, the name values should be formed into a single comma-delimited string.
My input:
$missedFridgeLog = [
[
"date" => "01/01/18",
"name" => "Medicine"
],
[
"date" => "01/01/18",
"name" => "Drugs"
],
[
"date" => "02/01/18",
"name" => "Medicine"
],
[
"date" => "02/01/18",
"name" => "Drugs"
]
];
I have tried implementing a solution from Implode or join multidimentional array with comma, but it did not work as desired.
Desired output:
[
[
'date' => '01/01/18',
'name' => 'Medicine,Drugs',
],
[
'date' => '02/01/18',
'name' => 'Medicine,Drugs',
]
]
$missedFridgeLog = [
[
"date" => "01/01/18",
"name" => "Medicine"
],[
"date" => "01/01/18",
"name" => "Drugs"
]
[
"date" => "02/01/18",
"name" => "Medicine"
],
[
"date" => "02/01/18",
"name" => "Drugs"
]
];
$byDates = [];
foreach ($missedFridgeLog as $mfg) {
$byDates[$mfg['date']][] = $mfg['name'];
}
$res = [];
foreach ($byDates as $date => $name) {
$res[] = [
'name' => join(',',$name),
'date' => $date
];
}
var_dump($res);
You need to search key, value pair everytime you make a insert or update to result array. use this function() to search associate array. If match then update with additional name info else make a new insert to result array.
function filter_array($array){
///$array your previous array data
$result = array();
foreach($array["missedFridgeLog"] as $m){
$flag = true;
foreach($result as $k=>$r) {
if (is_in_array($r, "date", $m["date"]) == "yes") {
$result[$k]["name"] = $r["name"] . ',' . $m["name"];
$flag = false;
break;
}
}
if($flag==true){
$result[] = $m;
}
}
return array("missedFridgeLog"=>$result);
}
function is_in_array($array, $key, $key_value){
$within_array = 'no';
foreach( $array as $k=>$v ){
if( is_array($v) ){
$within_array = is_in_array($v, $key, $key_value);
if( $within_array == 'yes' ){
break;
}
} else {
if( $v == $key_value && $k == $key ){
$within_array = 'yes';
break;
}
}
}
return $within_array;
}
May be this is not the best way to do this, but it will help
$arr['missedFridgeLog'] = [
[
'date' => '01/01/18',
'name' => 'Medicine1'
],
[
'date' => '02/01/18',
'name' => 'New Medicine2'
],
[
'date' => '01/01/18',
'name' => 'Drugs1'
],
[
'date' => '02/01/18',
'name' => 'Medicine2'
],
[
'date' => '01/01/18',
'name' => 'New Drugs1'
],
[
'date' => '02/01/18',
'name' => 'Drugs2'
]
];
echo "<pre>";
$new_arr = array();
$date = array();
foreach ($arr['missedFridgeLog'] as $k => $a) {
if (in_array($a['date'], $date))
continue;
$new_arr[$k]['name'] = $a['name'];
$new_arr[$k]['date'] = "";
foreach ($arr[missedFridgeLog] as $key => $val) {
if ($key != $k) {
if ($a['date'] == $val['date']) {
$date[] = $new_arr[$k]['date'] = $a['date'];
$new_arr[$k]['name'] .= ", " . $val['name'];
}
}
}
if (empty($new_arr[$k]['date']))
unset($new_arr[$k]);
}
print_r($new_arr);
You can try below :-
Input array :-
$chkArray = [
'missedFridgeLog' => [
'0' => [
'date' => '01/01/18',
'name' => 'Medicine'
],
'1' => [
'date' => '01/01/18',
'name' => 'Drugs'
],
'2' => [
'date' => '02/01/18',
'name' => 'Medicine'
],
'3' => [
'date' => '02/01/18',
'name' => 'Drugs'
],
'4' => [
'date' => '02/01/18',
'name' => 'My Drugs'
]
]
];
$i = 0;
$finalarray = array();
foreach($chkArray['missedFridgeLog'] as $key=>$value) {
$checkExist = array_search($value['date'], array_column($finalarray, 'date'), true);
if($checkExist !== false) {
$finalarray[$checkExist]['name'] = $finalarray[$checkExist]['name'].','.$value['name'];
}
else {
$finalarray[$i]['date'] = $value['date'];
$finalarray[$i]['name'] = $value['name'];
$i++;
}
}
print_r($finalarray);
OutPut :-
Array
(
[0] => Array
(
[date] => 01/01/18
[name] => Medicine,Drugs
)
[1] => Array
(
[date] => 02/01/18
[name] => Medicine,Drugs,My Drugs
)
)
Do not use:
More than one loop,
Nested loops,
in_array(), or
array_search().
You only need one loop to apply temporary grouping keys. When a date/group is encountered after the first time, append its name value to the group's name value. When finished iterating, re-index the array.
Code: (Demo)
$result = [];
foreach ($missedFridgeLog as $row) {
if (!isset($result[$row['date']])) {
$result[$row['date']] = $row;
} else {
$result[$row['date']]['name'] .= ",{$row['name']}";
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'date' => '01/01/18',
'name' => 'Medicine,Drugs',
),
1 =>
array (
'date' => '02/01/18',
'name' => 'Medicine,Drugs',
),
)
I have array with this format:
$components = [
[
'name' => 'ADIPIC ACID',
'cas' => '123',
'einecs' => '321'
],
[
'name' => 'ADIPIC ACID/DIMETHY- LAMINOHYDROXY- PROPYL DIETHYLENE- TRIAMINE COPOLYMER',
'cas' => '456',
'einecs' => '654'
]
]
I need to find each name which has a / character, break it and create a new entry in the $components array with cas and einecs being empty string.
Also the first part of the name will have cas and einecs values from the original entry.
Expected array:
$components = [
[
'name' => 'ADIPIC ACID',
'cas' => '123',
'einecs' => '321'
],
[
'name' => 'ADIPIC ACID',
'cas' => '456',
'einecs' => '654'
],[
'name' => 'DIMETHY- LAMINOHYDROXY- PROPYL DIETHYLENE- TRIAMINE COPOLYMER',
'cas' => '',
'einecs' => ''
]
]
How can I do this?
Quite crude I admit and it doesn't account for multiple / characters in a value but it does return the result expected.
foreach( $components as $index=> $arr ){
foreach( $arr as $key => $value ){
if( $key=='name' && strstr( $value, '/' ) ){
list($pre,$post)=explode('/',$value);
$components[$index][$key]=$pre;
$components[]=array('name'=>$post,'cas'=>'','einecs'=>'');
}
}
}
<?php
$components = [
[
'name' => 'ADIPIC ACID',
'cas' => '123',
'einecs' => '321'
],
[
'name' => 'ADIPIC ACID/DIMETHY- LAMINOHYDROXY- PROPYL DIETHYLENE- TRIAMINE COPOLYMER',
'cas' => '456',
'einecs' => '654'
]
];
$new = [];
foreach ($components as &$component) {
if ($items = explode('/', $component['name'])) {
$component['name'] = array_shift($items);
$new = array_merge($new, $items);
}
}
foreach ($new as $item) {
$components[] = ['name' => $item, 'cas' => '', 'einecs' => ''];
}
var_dump($components);
I would try something like this where I use the explode function using the '/' character on the name of each component. Then I'd create a new array of all the new components taking the values of the component being evaluated.
$newComponents = array();
foreach($components as $component) {
foreach(explode('/', $component['name']) as $newComponentName) {
$newComponents[] = array('name' =>$newComponentName,
'cas' => $component['cas'],
'einecs' => $component['einecs']);
}
}
foreach($components as $component)
{
if(strpos($component["name"],"/") !== false){
$temp = explode("/",$component["name"]);
$components[] = new array("name"=>$temp[1], "cas"=>"", "einecs"=>"");
}
}
I want to avoid if it is possible foreach combined with if. I want to search the array, take out the matches and create new one base on result.
In this example I want to create separate arrays for each os -
$os1 = $array;
$os2 = $array...
Array looks like this:
$array = [
0 => [
'id' => 1,
'name' => 'name',
'os' => 1
],
1 => [
'id' => 2,
'name' => 'name',
'os' => 1
],
2 => [
'id' => 3,
'name' => 'name',
'os' => 2
],
3 => [
'id' => 3,
'name' => 'name',
'os' => 2
]
];
Use array_filter to reduce the input array to the expected result
$os = 1;
$data = array_filter($array, function($item) use ($os) {
return $item['os'] == $os;
});
The short one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array('id' => $item['id'], 'name' => $item[$name];
}
The better one
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
switch($item['os']) {
case 1:
$os1[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 2:
$os2[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
case 3:
$os3[] = array('id' => $item['id'], 'name' => $item[$name]);
break;
default:
throw new Exception('Unknown Os');
}
}
Also you maybe want to assign array($item['id'] => $item[$name]); instead of array('id' => $item['id'], 'name' => $item[$name]);
$os1 = [];
$os2 = [];
$os3 = [];
foreach ($array as $item) {
${'os' . $item['os']}[] = array($item['id'] => $item[$name]);
}