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'],
];
}
Related
I want to prepare json with php as follows. But, the services section does not occur nested. How can I get json output as below by correcting php code?
foreach($this->input->post('name') as $key => $value){
$services = [];
foreach($this->input->post('services') as $value2){
$services[] = array(
'service_name' => $value2
);
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
echo json_encode($json);
I want this:
[
{
"name":"aa",
"surname":"bb",
"birthday":"10.07.2019",
"services":[
{
"service_name":"test1",
"service_name":"test2",
},
]
},
{
"name":"cc",
"surname":"dd",
"birthday":"20.07.2019",
"services":[
{
"service_name":"test3",
"service_name":"test4",
},
]
}
]
You can try following code:
foreach($this->input->post('name') as $key => $value){
$services = [];
$count = 0;
foreach($this->input->post('services') as $value2){
$services["service".$count] = $value2;
$count++;
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
$json = json_encode($json);
$json = preg_replace('/"service\d+"/', "service_name", $json);
echo $json;
I have 3 array like
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
$combo = array();
foreach ($arr['size'] as $size) {
foreach($arr['color'] as $color){
foreach ($arr['type'] as $type) {
$variant = json_encode(['size' => $size->name, 'color' =>
$color->name, 'type' => $type->name]);
array_push($combo,$variant);
}
}
}
echo $combo;
// result
0 => "{"size":"15 inch","color":"yellow","type":"metal"}"
1 => "{"size":"18 inch","color":"yellow","type":"plastic"}"
It works properly but but there is can be less or more variants. How can I handle this.
For example
$arr = [
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
Or
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
]
For what i understand, you have to combine the arrays of properties into one array of
object.
I have to leave now, but if you need a explanation leave a comment and i updated the answers
$arr = [
"color" => [["name"=>"red"],['name'=>'yellow']],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
];
function runFor($arr ,&$array, $keys,$index,&$positions){
foreach ($arr[$keys[$index]] as $key => $espec){
$positions[$keys[$index]] = $key;
if($index + 1 < count($keys)){
runFor($arr,$array,$keys, $index+1,$positions);
}else{
$item = (object)[];
foreach ($keys as $key){
$item->$key = $arr[$key][$positions[$key]]['name'];
}
array_push($array,$item);
}
unset($positions[$keys[$index]]);
}
}
$array = array();
$keys = array_keys($arr);
$positions = [];
runFor($arr,$array,$keys,0,$positions);
$combo = array();
foreach ($array as $item){
array_push($combo,json_encode($item));
}
var_dump($combo);
my array image just like this, if subarray "name" is empty or null i want delete array, how to do that ?
here my current script
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
unset($data[0]); //delete first row
$data = array_values($data);
//loop search data
var_dump ($data);
die();
Assume that you have the following data set,
$array = [
[
'name' => 'not null', 'phone' => 12546
],[
'name' => '', 'phone' => 852147
],[
'name' => null, 'phone' => 96325874
],[
'name' => 'have value', 'phone' => 12546
],
];
You can filter the nulled or empty values like several ways :
1-
foreach ($array as $key => &$value) {
if (empty($value['name']) || is_null($value['name'])) {
$value = null;
}
}
$array = array_filter($array);
2-
$newData = [];
foreach ($array as $key => $value) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
}
3- using array_walk
$newData = [];
array_walk($array, function ($value, $key) use (&$newData) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
});
4- using array_filter
$newData = array_filter($array, function ($value) {
if (!empty($value['name']) && !is_null($value['name'])) {
return $value;
}
});
<?php
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
if($this->split_name($row['B'])!=='' && $this->split_name($row['B'])!==NULL){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
}
//loop search data
var_dump ($data);
die();
I simple put an if condition inside your loop so you can check if your value is null or empty and if it is then you don't fill your new array. Also moved your counter inside the if so you increment it only in a success array push
A more "elegant" way for your if condition is this as well:
if (!empty($this->split_name($row['B'])) && !is_null($this->split_name($row['B'])))
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',
),
)
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.