I get an additional arraydimension and I don't really know why. This is the php code I use for my multidimensional array.
$json_arr = array(
"a" => "0",
"b" => 1,
"c" => 2);
$json_arr_d = array();
for ($i=0; $i<$rows*$cols; $i++) {
$json_arr_d[] = array(
"d1" => "$i",
"d2" => "0",
"d3" => rand(0, 2)
);
}
$json_arr_e = array();
for ($i=0; $i<6; $i++) {
$json_arr_e[] = array(
"e1" => $i,
"e2" => "0",
"e3" => rand(0, 1),
"e4" => false
);
}
$json_arr[] = array("d" => $json_arr_d);
$json_arr[] = array("e" => $json_arr_e);
$json = json_encode($json_arr);
As you can see in the following result. There are additional layers [0] and [1] for my d & e array.
{
"a":"ABXD",
"b":5,
"c":6,
"0":{ // HERE IS THE PROBLEM
"d":[
{
"d1":"0",
"d2":"1",
"d3":1
},
{
"d1":"1",
"d2":"2",
"d3":1,
}
},
"1":{ // HERE IS THE PROBLEM
"d":[
{
"d1":"0",
"d2":"1",
"d3":1,
"d4":false
},
{
"d1":"1",
"d2":"2",
"d3":0,
"d4":false
}
]
}
Maybe I am to sleepy already and it is a pretty simple solution or my way to add the arrays is fundamentally wrong.
Don't push onto the array, assign to the key you want.
$json_arr['d'] = $json_arr_d;
$json_arr['e'] = $json_arr_e;
Related
$myArray = [
"ID" => "",
"Module" => "",
"Version"=> ""
];
Output:
[
{23,finance,1.0},
{24,finance,1.1},
{25,logistic,1.0}
]
I have an array with the given Keys like above. I need a new array that gives me the highest Version IF module is same. How would I do that?
desired Output:
[
{24,finance,1.1},
{25,logistic,1.0}
]
This is what I tried
$modulesFiltered = [];
$i = 0;
$j = 0;
foreach($modules as $module){
$modulesFiltered[$i]['ID'] = $module['ID'];
foreach($modulesFiltered as $moduleF){
if(!empty($moduleF[$j]['Module'])){
if($module[$i]['Module'] == $moduleF[$j]['Module']){
$modulesFiltered[$i]['Module'] = 'this is doubled';
}
} else {
$modulesFiltered[$i]['Module'] = $module['Module'];
}
$j++;
}
$modulesFiltered[$i]['Module'] = $module['Module'];
$i++;
}
I tried to debug your code though.The problem is that you try to access element [0] of $moduleF. You should change $moduleF[$j]['Module'] to $moduleF['Module'].
Use standard functions where possible. for finding values within (multidimensional) array's you can use array_search. The code beneath works.
Also don't compare strings with == use strcmp(str1, str2) == 0 instead
$inputArray = array(
array(
"ID" => 23,
"Module" => "finance",
"Version"=> 1.0),
array(
"ID" => 24,
"Module" => "finance",
"Version"=> 1.1),
array(
"ID" => 25,
"Module" => "logistiscs",
"Version"=> 1.0));
$output = array();
foreach($inputArray as $element)
{
$key = array_search($element["Module"], array_column($output, "Module"));
if(is_numeric($key))
$output[$key]["Version"] = max($element["Version"], $output[$key]["Version"]);
else
$output[] = $element;
}
print_r($output);
Please find below the code sample for adding repeated values inside inner array. Can anyone suggest an alternative way to add the values faster? The code will work with smaller arrays, but I want to add big arrays that contain huge amount of data. Also I want to increase execution time.
<?php
$testArry = array();
$testArry[0] = array(
"text" => "AB",
"count" => 2
);
$testArry[1] = array(
"text" => "AB",
"count" => 5
);
$testArry[2] = array(
"text" => "BC",
"count" => 1
);
$testArry[3] = array(
"text" => "BD",
"count" => 1
);
$testArry[4] = array(
"text" => "BC",
"count" => 7
);
$testArry[5] = array(
"text" => "AB",
"count" => 6
);
$testArry[6] = array(
"text" => "AB",
"count" => 2
);
$testArry[7] = array(
"text" => "BD",
"count" => 111
);
$match_key = array();
$final = array();
foreach ($testArry as $current_key => $current_array) {
$match_key = array();
foreach ($testArry as $search_key => $search_array) {
$key = '';
if ($search_array['text'] == $current_array['text']) {
$match_key[] = $search_key;
$key = $search_array['text'];
if (isset($final[$key])) {
$final[$key] += $search_array['count'];
} else {
$final[$key] = $search_array['count'];
}
}
}
for ($j = 0; $j < count($match_key); $j++) {
unset($testArry[$match_key[$j]]);
}
}
print_r($final);
?>
Anyway to add memory during the execution time?
Thank you.
One array_walk will be enough to solve your problem,
$final = [];
array_walk($testArry, function($item) use(&$final){
$final[$item['text']] = (!empty($final[$item['text']]) ? $final[$item['text']] : 0) + $item['count'];
});
print_r($final);
Output
Array
(
[AB] => 15
[BC] => 8
[BD] => 112
)
Demo
array_walk — Apply a user supplied function to every member of an array
array_map() - Applies the callback to the elements of the given arrays
array_key_exists() - Checks if the given key or index exists in the array
You can use array_walk and array_key_exists to iterate through the array element and sum the one which has text index same
$res = [];
array_map(function($v) use (&$res){
array_key_exists($v['text'], $res) ? ($res[$v['text']] += $v['count']) : ($res[$v['text']] = $v['count']);
}, $testArry);
I have 3 objects and I want them to combine into 1 array. There are duplicate property names in objects, but I want them too (with renames property name). How can I do that?
$object1 = {
"id": "10",
"unit_number": "12565"
},
$object2 = {
"id": "20",
"full_name": "Lorem Ipsm"
},
$object3 = {
"id": "30",
"phone": "123456789"
}
I want the output like,
array = (
"id1" => "10",
"unit_number" => "12565",
"id2" => "20",
"full_name" => "Lorem Ipsm",
"id3" => "30",
"phone" => "123456789"
);
I have tried to assign them to one array like,
$arr = array();
$arr['obj1'] = $object1;
$arr['obj2'] = $object2;
$arr['obj3'] = $object3;
Now I thought of doing a foreach, but I am stuck. My actual object is too big. So there are many duplicates. Not just this one.
I think you can achieve this using below code,
$object1 = (object) ['id' => '10', "unit_number"=> "12565", "name" => 'Test name'];
$object2 = (object) ['id' => '20', "full_name"=> "Lorem Ipsm"];
$object3 = (object) ['id' => '30', "phone"=> "123456789", "name" => "test name 1"];
$array1 = (array) $object1;
$array2 = (array) $object2;
$array3 = (array) $object3;
function array_merge_dup_keys() {
$arrays = func_get_args();
$data = array();
foreach ($arrays as $a) {
foreach ($a as $k => $v) {
$key1 = check_key_exists($k,$data);
$data[$key1] = $v;
}
}
return $data;
}
function check_key_exists($key,$array,$loop_count=1)
{
if(array_key_exists ( $key , $array ))
{
$val = explode('_',$key);
$count = isset($val[1]) ? $val[1] : $loop_count;
$start_key = isset($val[0]) ? $val[0] : $key;
$key = $start_key.'_'.$loop_count;
$key = check_key_exists($key,$array,$count+1);
}
return $key;
}
$data = array_merge_dup_keys($array1 ,$array2,$array3);
The output ($data) of above code will be,
Array
(
[id] => 10
[unit_number] => 12565
[name] => Test name
[id_1] => 20
[full_name] => Lorem Ipsm
[id_2] => 30
[phone] => 123456789
[name_1] => test name 1
)
Maybe something like this? (untested, possible typos/syntax errors...)
// this looks like json, not PHP
// "object1": {
// "id": "10",
// "unit_number": "12565"
// },
// "object2": {
// "id": "20",
// "full_name": "Lorem Ipsm"
// },
// "object3": {
// "id": "30",
// "phone": "123456789"
// }
// here is a php array for that data
$objArray = array(
"object1" => array( "id"=>"10", "unit_number"=>"12565"),
"object2" => array( "id"=>"20", "full_name"=>"Lorem Ipsm"),
"object3" => array( "id"=>"30", "phone"=>"123456789")
);
$newArray = array();
foreach( $objArray as $key=>$value)
{
// the the id "append"
$idAppend = substr($key, strlen("object"));
foreach($value as $subkey=>$subvalue)
{
$newkey = $subkey;
if ( strcmp($subkey, "id") == 0 ) // it is the id string
{
$newkey = $subkey.$idAppend;
}
$newArray[$newkey] = $subvalue;
}
}
I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php
I have to create a array dynamically like I have a method which will pass keys and based on those keys I need to create arrays inside them
Format will be like-
{
"TEST1":{
"140724":[
{
"A":"1107",
"B":4444,
"C":"1129",
"D":"1129"
},
{
"A":"1010",
"B":2589,
"C":"1040",
"D":"1040"
}
],
"140725":[
]
}
}
So how should I frame this logic inside for loop. I am new to php so formatting the same creating trouble.
$json_Created = array("TEST1" => array());
foreach($val as $key=>$value){
array_push($json_created,array($key = array()));
}
The entire array is dynamic, so like I have 140724 ,,, till 140731 (actually date format yymmdd), any amount if numbers can be considered. SO that part is dynamic moreover some dates may be wont have any values and some will have.
So my main point is to develop that logic so that irrespective the
number of inputs , my array formation must be intact.
You can use json_encode with array to do so
$array = array(
"TEST1" => array(
"140724" => array(
array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
),
array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
)
),
"140725" => array(
)
)
);
echo json_encode($array);
Another way to construct array is
$array = array();
$array["TEST1"]["140724"][] = array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
);
$array["TEST1"]["140724"][] = array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
);
$array["TEST1"]["140725"] = array();
echo json_encode($array);
Finally managed to write the code-
$keys_content = array("starttime", "id", "duration", "endtime");
$dates = array();//140724,140725,140726140727
$mainID =“TEST1”;
$arraySuperMain = array();
$arrayMain = array();
for ($j = 0; $j < count($dates); $j++) {
$array_main = array();
$subset = array();
for ($i = 0; $i < count($keys_content); $i++) {
$key = $keys_content[$i];
$subset = array_push_assoc($subset, $key, "Value".$i);
}
$array_main = array_push_assoc($array_main, $dates[$j], $subset);
array_push($arrayMain, $array_main);
}
$createdJSON = array_push_assoc($arraySuperMain, $mainID, $arrayMain);
public static function array_push_assoc($array, $key, $value) {
$array[$key] = $value;
return $array;
}