(PHP) Initialize empty multidimensional array and then fill it - php

I want to create an array with 3 types of information: name, id, and work.
First I want to just initialize it, so that I can later fill it with data contained in variables.
I searched how to initialize a multidimensional array, and how to fill it, and that's what I came up with:
$other_matches_info_array = array(array());
$other_matches_name = "carmen";
$other_matches_id = 3;
$other_matches_work = "SON";
array_push($other_matches_info_array['name'], $other_matches_name);
array_push($other_matches_info_array['id'], $other_matches_id);
array_push($other_matches_info_array['work'], $other_matches_work);
This is what I get when I print_r the array:
Array
(
[0] => Array
(
)
[name] =>
)
What did I do wrong?

very short answer:
$other_matches_info_array = array();
// or $other_matches_info_array = []; - it's "common" to init arrays like this in php
$other_matches_name = "carmen";
$other_matches_id = 3;
$other_matches_work = "SON";
$other_matches_info_array[] = [
'id' => $other_matches_id,
'name' => $other_matches_name
];
// so, this means: new element of $other_matches_info_array = new array that is declared like this.

You can simply create it like so:
$arrayMultiDim = [
[
'id' => 3,
'name' => 'Carmen'
],
[
'id' => 4,
'name' => 'Roberto'
]
];
Then later to add to just say:
$arrayMultiDim[] = ['id' => 5, 'name' => 'Juan'];

Try code below:
$other_matches_info_array_main = [];
$other_matches_name = "carmen";
$other_matches_id = 3;
$other_matches_work = "SON";
$other_matches_info_array['name'] = $other_matches_name;
$other_matches_info_array['id'] = $other_matches_id;
$other_matches_info_array['work'] = $other_matches_work;
$other_matches_info_array_main[] = $other_matches_info_array;
Demo

Related

Change array style in PHP [duplicate]

This question already has answers here:
PHP Append an array to a sub array
(2 answers)
Closed 6 months ago.
i've been trying to make this array
$data = array (
'country' => '+57',
'message' => 'test',
'messageFormat' => 0,
'addresseeList' =>
array (
0 =>
array (
'mobile' => '1111',
'correlationLabel' => 'corelation ejemplo',
),
)
);
into this
$data = array();
$data['country'] = '+57';
$data['message'] = 'test';
$data['messageFormat'] = 0;
$data['addresseeList'] = array(
$data['mobile'] = '1111',
$data['correlationLabel'] = 'corelation ejemplo'
);
But when i try to convert this array into a json object i'm getting this
string(154) "{"country":"+57","message":"test","messageFormat":0,"mobile":"1111","correlationLabel":"corelation ejemplo","addresseeList":["1111","corelation ejemplo"]}"
but i should get something like this
string(128) "{"country":"+57","message":"test","messageFormat":0,"addresseeList":[{"mobile":"1111","correlationLabel":"corelation ejemplo"}]}"
Thanks in advance
The way you are inserting the address info actually places the mobile and correlationLabel at the root of the $data array.
instead, you need to add create an entirely new array to place as the only element inside an array you create at $data['addresseeList'].
$data = array();
$data['country'] = '+57';
$data['message'] = 'test';
$data['messageFormat'] = 0;
$data['addresseeList'][] = array(
'mobile' => '1111',
'correlationLabel' => 'corelation ejemplo'
);
echo json_encode($data, JSON_PRETTY_PRINT).PHP_EOL;

php object and array

I'm trying to write to a variable inside an object and I can't find how to do it.
Array
(
[0] => stdClass Object
(
[id] => 3
[rota_name] => Tea and coffee
[rota_owner_name] => 9
[rota_notes] =>
[rota_entry] => {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}
[rota_advance_email_days] =>
[rota_reminder_sent] =>
)
I want to change person 8 to person 9
So I think that I need to get the rota_entry (using foreach) and then use Json_decode to get an array and then something but my brain now hurts :( I and don't know how to reset it back up to put into the database again.
I can find lots that talks about simple JSON decode or simple array parsing but not something to help with this
This code assumes $obj = the first entry in your array you show.
So $obj = Array[0]
$json = json_decode($obj->rota_entry);
$json->rota_entry0->person = 9;
$obj->rota_entry = json_encode($json);
This code changes rota_entry0 person 8 to 9
// Your original array
$array = [
0 => (object) [
'id' => 3,
'rota_name' => 'Tea and coffee',
'rota_owner_name' => 9,
'rota_notes' => '',
'rota_entry' =>' {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}',
'rota_advance_email_days' => '',
'rota_reminder_sent' => '',
]
];
// Create an empty object to replace the rota_entry key in the array
$rotaEntry = (object) [];
// Iterate through the original rota_entry and replace "person"
foreach (json_decode($array[0]->rota_entry) as $key => $value) {
// You can set whatever logic you want here
// For example: if ($key == "rota_entry4") {$value->person = 4;}
// I'm hardcoding "9"
$value->person = 9;
$rotaEntry->$key = $value;
}
// Assign the newly created (and modified) rotaEntry back to the original array
$array[0]->rota_entry = $rotaEntry;
Try this:
$array = (array) $object;
foreach($array as &$value){
$json = json_encode($value['rota_entry']);
$json -> rota_entry0 -> person = 9;
$value['rota_entry'] = json_encode($json);
}
$array = (object) $array;
good luck.

Remove array items based on sub array duplicate values and then sort in custom order

Remove array items based on duplicate values that appear 1 level deeper inside the array. Once the items have been sorted of duplicates, then would be cool to re order the new array.
This is the current input array...
$downloads = [
['type' => 'PHOTOS'],
['type' => 'DOCUMENTS'],
['type' => 'DOCUMENTS'],
['type' => 'VIDEOS'],
['type' => 'PHOTOS'],
];
I would like to remove all duplicates from this input so I am left with this new output...
[
['type' => 'PHOTOS'],
['type' => 'DOCUMENTS'],
['type' => 'VIDEOS'],
]
But is it possible to set and ordering to each TYPE value. For example can I set predetermined orders using a variables or something. Any advice on re-ordering the new array to a specific order. Using this new order...
$photos = 1;
$videos = 2;
$documents = 3;
or a new order using an array maybe...
$new_order = array(
1 => 'PHOTOS',
2 => 'VIDEOS',
3 => 'DOCUMENTS'
)
Any help would be so good. I've tried array_unique and array_map but I can't seem to find out how to specify which sub array key to check for duplicates.
This is what i've tried so far...
$downloads = get_field('downloads');
$types = array_unique($downloads));
and
$downloads = get_field('downloads');
$types = array_map("unserialize", array_unique(array_map("serialize", $downloads)));
I didn't get as far as re ordering the array.
The solution using array_column, array_map, array_search and usort functions:
$new_order = array(
0 => 'PHOTOS',
1 => 'VIDEOS',
2 => 'DOCUMENTS'
);
// $downloads is your input array
$types = array_map(function ($v) {
return ['TYPE' => $v];
},array_unique(array_column($downloads, 'TYPE')));
usort($types, function($a, $b) use($new_order){
$a_key = array_search($a['TYPE'], $new_order);
$b_key = array_search($b['TYPE'], $new_order);
if ($a_key == $b_key) return 0;
return ($a_key < $b_key)? -1 : 1;
});
print_r($types);
The output:
Array
(
[0] => Array
(
[TYPE] => PHOTOS
)
[1] => Array
(
[TYPE] => VIDEOS
)
[2] => Array
(
[TYPE] => DOCUMENTS
)
)
Quick and dirty solution for removing "subarray" duplicates:
$a = [];
$a[]['type'] = 'photos';
$a[]['type'] = 'documents';
$a[]['type'] = 'documents';
$a[]['type'] = 'videos';
$a[]['type'] = 'photos';
$b = [];
foreach( $a as $index => $subA ) {
if( in_array($subA['type'], $b) ) {
unset($a[$index]);
} else {
$b[] = $subA['type'];
}
}
Regarding the sorting: Just set the indices with the order you need them and after removing the duplicates use ksort (assuming I did understand you right).
Simply use array_intersect that computes common part of two arrays. If you use order array as first argument, order of that will be preserved.
Your input:
$input = [
['TYPE' => 'PHOTOS'],
['TYPE' => 'DOCUMENTS'],
['TYPE' => 'DOCUMENTS'],
['TYPE' => 'VIDEOS'],
['TYPE' => 'PHOTOS']
];
I've write simple function to achieve all of your needs:
function do_awesomness($input, $key = 'TYPE', $order = ['PHOTOS', 'VIDEOS', 'DOCUMENTS'])
{
$result = [];
foreach($input as $k => $value)
$result[] = $value[$key];
$result = array_unique($result);
return array_values(array_intersect($order, $result));
}
Usage:
do_awesomness($input);
Working example: http://phpio.net/s/1lo1
You can use array_reduce to reimplement array_unique, but collecting unique types in order of appearance. This will help us to sort array later.
$order = [
'PHOTOS' => 1,
'VIDEOS' => 2,
'DOCUMENTS' => 3
];
$types = [];
$uniqueDownloads = array_reduce(
$downloads,
function ($uniqueDownloads, $download) use (&$types, $order) {
$type = $download['TYPE'];
if (!isset($types[$type])) {
$types[$type] = isset($order[$type]) ? $order[$type] : 0;
$uniqueDownloads[] = $download;
}
return $uniqueDownloads;
},
[]
);
array_multisort($types, $uniqueDownloads);
Traversing the array we check whether the type key exists in $types. If it exists skip this element. Otherwise, set this key and assign value from $order to it (this will be used for sorting).
We then use array_multisort to sort $uniqueDownloads by sorting $types.
Here is working demo.
Read more about anonymous functions. I have passed $types by reference with & so the function change value of the original array, but not the value of the copy.
For custom ordering I recommended usort:
$array = [
['TYPE'=>'PHOTOS'],
['TYPE'=>'DOCUMENTS'],
['TYPE'=>'VIDEOS']
];
function customOrder($a, $b){
$newOrder = [
'PHOTOS' => 1,
'VIDEOS' => 2,
'DOCUMENTS' => 3
];
$valA = (array_key_exists($a['TYPE'],$newOrder))?$newOrder[$a['TYPE']]:999;
$valB = (array_key_exists($b['TYPE'],$newOrder))?$newOrder[$b['TYPE']]:999;
if($valA > $valB){
$result = 1;
} elseif($valA < $valB){
$result = -1;
} else {
$result = 0;
}
return $result;
}
usort($array, "customOrder");
var_dump($array);
Because your ordering array appears to be an exhaustive list of possible download values, you can just filter that static array by the downloads values.
Code: (Demo)
var_export(
array_intersect(
$new_order,
array_column($downloads, 'type')
)
);
If there may be values in the downloads array that are not represented in the ordering array, then the sample data in the question should be adjusted to better represent the application data.

Multidimensional Array modify values

I'd changed, the data in this line.
$fileConv = $_GET['file']; // It retrieves data to add.
$file = intval($fileConv); // Conversion
$ArrayNotes = array (
0 => array ('titre' => 'aaa','ref' => 'aaa','date' => 'aaa','like' => aaa,'url' => 'aaa'),
1 => array ('titre' => 'aaa1','ref' => 'aaa1','date' => 'aaa1','like' => aaa1,'url' => 'aaa1') // my array
);
$like = $ArrayNotes[$file]['like'] + 1; // The only data that changes.
$donnee = array("titre" => $ArrayNotes[$file]['titre'], "ref" => $ArrayNotes[$file]['ref'],"date" => $ArrayNotes[$file]['date'], "like" => $like, "url" => $ArrayNotes[$file]['url']); // Change Data
As stated, I want to know how to change this data directly.
Example : To add a new line :
array_push($ArrayNotes, $donnee);
$var_str = var_export($ArrayNotes, true);
$var = "<?php\n\n\$ArrayNotes = $var_str;\n\n?>";
file_put_contents('content.php', $var);
Thanks you for your help.
Should be as easy as the following:
$ArrayNotes[$file]['like'] = 1234;
And if you just wish to add one to the existing field, you may do:
$ArrayNotes[$file]['like'] += 1;

How to group by and sum a multi-dimensional array?

I have already seen this
stackoverflow page but it is not helping me.
I want to group by two columns and sum the values of a third column.
If the discount_id and dis_percent are the same then add the discount_value.
Here is my array:
$dis = [
[['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '7.500'], ['Dis_val' => '192.75']],
[['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '97.88']],
[['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '5.000'], ['Dis_val' => '39.90']],
[['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '99.90']]
];
The output that I need is:
D1-Dis1->7.5->192.75
D1-Dis1->5.0->39.9
D1-Dis2->2.5->197.78
My code looks like this:
$newarr = array();
$reverse_map = array();
foreach($dis as $idx => $entry) {
if (isset($reverse_map[$entry['Dis_id']])) {
// have we seen this name before? retrieve its original index value
$idx = $reverse_map[$entry['Dis_id']];
} else {
// nope, new name, so store its index value
$reverse_map[$entry['Dis_id']] = $idx;
}
// copy the 'constant' values
$newarr[$idx]['Dis_id'] = $entry['Dis_id'];
$newarr[$idx]['Dis_per'] = $entry['Dis_per'];
// sum the qtd_post values to whatever we previously stored.
foreach($entry['Dis_val'] as $x => $y) {
$newarr[$idx]['Dis_val'][$x] += $y;
}
}
This is the solution I've come up with based off of the understanding that your intended array structure was as so;
$dis = array(
array(
'Dis_id' => 'Dl-Dis1',
'Dis_per' => 7.500,
'Dis_val' => 192.75
),
...
);
It determines the solution by creating a multidimensional array where the first dimension is the Dis_id, and the second dimension is the Dis_per, and the value becomes the sum of the Dis_val;
$sums = array();
foreach ($dis as $entry) {
if (!isset($sums[$entry['Dis_id']])) {
$sums[$entry['Dis_id']] = array();
}
if (!isset($sums[$entry['Dis_id']]["{$entry['Dis_per']}"])) {
$sums[$entry['Dis_id']]["{$entry['Dis_per']}"] = 0;
}
$sums[$entry['Dis_id']]["{$entry['Dis_per']}"] += $entry['Dis_val'];
}
See this working example; https://eval.in/158661
As you iterate your input array, you will need to isolate the Dis_id and Dis_per values and use them as keys when storing your Dis_val.
If there no value present for a [Dis_id][Dis_per] element, then you can simply store the value. If there is a pre-existing value, you need to add the new value to the stored value. isset() is most efficient function to aid in the identification of new/existing elements in the result array.
Code: (Demo)
$dis = [
[['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '7.500'], ['Dis_val' => '192.75']],
[['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '97.88']],
[['Dis_id' => 'Dl-Dis1'], ['Dis_per' => '5.000'], ['Dis_val' => '39.90']],
[['Dis_id' => 'Dl-Dis2'], ['Dis_per' => '2.500'], ['Dis_val' => '99.90']]
];
foreach ($dis as $group) {
$id = $group[0]['Dis_id'];
$per = $group[1]['Dis_per'];
if (!isset($result[$id][$per])) {
$result[$id][$per] = $group[2]['Dis_val'];
} else {
$result[$id][$per] += $group[2]['Dis_val'];
}
}
var_export($result);
Output:
array (
'Dl-Dis1' =>
array (
'7.500' => '192.75',
'5.000' => '39.90',
),
'Dl-Dis2' =>
array (
'2.500' => 197.78,
),
)

Categories