Multidimensional Array modify values - php

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;

Related

session variable name as a variable?

I try to make a session variable where the session variable name should be diffrent, and therefore i make the session variable name a variable name:
$nummer = $_POST['nummer'];
$num = $nummer;
$vareInfo = array(
"vareNummer" => "$nummer",
"vareNavn" => "$vare",
"varePris" => $pris,
"vareBillede" => $VarBillede,
"vareAntal" => $antal
);
$_SESSION[$num] = $vareInfo;
$_SESSION[$pris] = "hukabuka";
but i dosen't work, i just changeching the the other sessioen to the new value?
it output this:
Array ( [vareNummer] => 182162
[vareNavn] => Solsikke
[varePris] => 120
[vareBillede] => 63c7cba6cac6d7.24544415.jpg
[vareAntal] => 1
)
and next time i run it it changing it instead of making a new
To prevent that your session gets overwritten add a check if the session already exists.
That way it only gets created once for each unique $num
$nummer = $_POST['nummer'];
$num = $nummer;
$vareInfo = array(
"vareNummer" => "$nummer",
"vareNavn" => "$vare",
"varePris" => $pris,
"vareBillede" => $VarBillede,
"vareAntal" => $antal
);
if(!isset($_SESSION[$num])){
$_SESSION[$num] = $vareInfo;
}
if(!isset($_SESSION[$pris])){
$_SESSION[$pris] = "hukabuka";
}
An example how this can be made to work (using PHP 8.2):
my_form.html:
<form action="do_stuff.php" method="POST">
<input id="data1" name="data1" type="text">
<input id="data2" name="data2" type="text">
<input type="submit" value="Do">
</form>
do_stuff.php:
<?php
session_start();
$nummer = $_POST['data1'];
$num = $nummer;
$pris = $_POST['data2'];
$vareInfo = array(
"vareNummer" => "$nummer",
"varePris" => $pris
);
$_SESSION['my_data'][$num] = $vareInfo;
$_SESSION['my_data'][$pris] = "hukabuka";
// or, the session variables can be set using a prefix:
//$_SESSION['my_data_' . $num] = $vareInfo;
?>
EDIT ADD:
An example session data from posting twice from the form using two unique data1 values would be as shown below. The values are 1234 and 7890.
Array (
[my_data] =>
Array (
[1234] => Array ( [vareNummer] => 1234 [varePris] => 55 )
[55] => hukabuka
[7890] => Array ( [vareNummer] => 7890 [varePris] => 99 )
[99] => hukabuka
)
)
Check the session with that variable, if already set with that index then do not over write the session value
you can use either isset or !empty in php
<?php
$nummer = $_POST['nummer'];
$num = $nummer;
$vareInfo = array(
"vareNummer" => "$nummer",
"vareNavn" => "$vare",
"varePris" => $pris,
"vareBillede" => $VarBillede,
"vareAntal" => $antal
);
if(!empty($_SSESSION[$num])) {
$_SESSION[$num] = $vareInfo;
}
if(!empty($_SESSION[$pris])) {
$_SESSION[$pris] = "hukabuka";
}
?>

(PHP) Initialize empty multidimensional array and then fill it

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

PHP - processing array values

I have an array that contains DNS records and looks like this
Array ( [domain] => xxxx.com [record_id_+++711753] => 711753 [host_+++711753] => # [type_+++711753] => A [priority_+++711753] => [value_+++711753] => 80.82.72.12 [record_id_+++711752] => 711752 [host_+++711752] => www [type_+++711752] => A [priority_+++711752] => [value_+++711752] => 80.82.72.12 [record_id_+++711754] => 711754 [host_+++711754] => # [type_+++711754] => MX [priority_+++711754] => 20 [value_+++711754] => fallback.denit.net [record_id_+++711755] => 711755 [host_+++711755] => # [type_+++711755] => MX [priority_+++711755] => 10 [value_+++711755] => ms.denit.net [record_id_+++711756] => 711756 [host_+++711756] => mail [type_+++711756] => A [priority_+++711756] => [value_+++711756] => 62.148.185.22 [record_id_+++711757] => 711757 [host_+++711757] => autodiscover [type_+++711757] => CNAME [priority_+++711757] => [value_+++711757] => autoredirect.mshex.nl [record_id_+++1148031] => 1148031 [host_+++1148031] => webmail [type_+++1148031] => CNAME [priority_+++1148031] => [value_+++1148031] => webmail.mshex.nl )
_+++ is a delimiter between the record_id and the type of DNS value.
I need to talk to an API to update records. It works like this (example);
$mdr->addParam( "command", "dns_record_modify" );
$mdr->addParam( "domein", "xxx" );
$mdr->addParam( "tld", "com" );
$mdr->addParam( "record_id", "461741" );
$mdr->addParam( "host", "#" );
$mdr->addParam( "address", "mail2.xxx.com" );
$mdr->addParam( "priority", "20" );
I know that I can use explode to fill the API values, domain and TLD.
However I cant seem to find a way to group the array values by record_id and fire a request per record_id that combines multiple values like host, type and priority.
How should I achieve this?
You're correct about using the explode() method. IMO this is the best approach to the solution. I updated the answer because of the slight typo error and also added a working version. See it here.
# loop each entry
foreach($array as $key => $value)
{
# [0] - record_id
# [1] / $value - 711753
# check that the key isn't domain since it doesn't contain _++
if($key != 'domain')
{
$mdr->addParam(explode('_+++', $key)[0], $value);
}
else
{
$mdr->addParam($key,$value);
}
}
The above code snippet explodes the _+++ out of the key to find the callback value. The $value then holds the corresponding data callback and then each is passed through your instanced object in the method addParam().
Since the callback domain in your array keys does not contain the _+++ brace, I did a check before using the explode() method.
To group the array values by record_ids, you could create a new, multidimensional array and use the record IDs as top-level keys. Here's an example:
$data = array();
$data['domain'] = 'xxxx.com';
$data['record_id_+++711753'] = 711753;
$data['host_+++711753'] = '#';
$data['type_+++711753'] = 'A';
$data['type_+++1148031'] = 'CNAME';
$data['host_+++1148031'] = 'webmail';
$sorted_data = [];
foreach($data as $key=>$val){
$key_info = explode('_+++', $key);
if (count($key_info) > 1){
$record_id = $key_info[1];
$key_name = $key_info[0];
$sorted_data[$record_id][$key_name] = $val;
}
}
var_dump($sorted_data);
You could transform your data to another structure, and then produce the $mdr->addParam calls from that:
$domain = $data["domain"]; // "xxx.com"
$tld = end(explode(".", $domain)) "com"
$domain = substr($domain, count($domain)-count($tld)-1); // "xxx"
$updates = [];
foreach ($data as $key => $value) {
$parts = explode("_+++", $key);
if (count($parts) != 2) continue;
list($key, $rec) = $parts;
if ($key == "value") $key = "address";
$updates[$rec][$key] = $value;
}
$updates will be something like this:
Array(
[711753] => Array (
[record_id] => 711753
[host] => #
[type] => A
[priority] =>
[address] => 80.82.72.12
),
[711752] => Array (
[record_id] => 711752
[host] => www
[type] => A
[priority] =>
[address] => 80.82.72.12
),
...
Then from that, you continue:
foreach($updates as $update) {
$mdr = new .... // some code to create new instance
$mdr->addParam( "command", "dns_record_modify");
$mdr->addParam( "domein", $domain);
$mdr->addParam( "tld", $tld);
foreach($update as $key => $value) {
$mdr->addParam($key, $value);
}
// execute mdr ...
}

Php array and json

help me to convert the following array in to json.
I tried to convert the array.
Array
(
[0] => Array
(
[c_code] => 200001
[itemname] => 303 10CAP
[c_pack_code] => PK0075
[c_web_img_link] =>
)
[1] => Array
(
[c_code] => 200005
[itemname] => 3P 4TAB
[c_pack_code] =>
[c_web_img_link] =>
)
)
current result for the following code is
public function searchOrder($idx, $data) {
if (!empty($data)) {
$result = OrderbukModel::func_get_searchlist($idx,$data);
if (!empty($result)) {
$resultArray[] = $result;
print_r(json_encode($result));
} else {
$resultArray[$idx] = ["Mysql returns empty result !"];
print_r(json_encode($resultArray));
exit;
}
}
}
now i got the result is like
[{"c_code":"200001","itemname":"303 10CAP","c_pack_code":"PK0075","c_web_img_link":""},{"c_code":"200005","itemname":"3P 4TAB","c_pack_code":"","c_web_img_link":""}]
But I need the result as follows
[{"c_code":"2000001","c_code":"200005"},
{"itemname":"303 10CAP","itemname":"3P 4TAB"},
{"c_pack_code":"PK0075","c_pack_code":""},
{"c_web_img_link":"","c_web_img_link":""}]
Example of how you can you make the json from array. Collect the data in two different array and after loop marge them and store the result in another array after that encode them.
Note: Your desired JSON is not a valid format, you can't use same index
for two data.
Online Example: https://3v4l.org/kdPDI
$arr = array(
array(
'c_code' => '200001',
'itemname' => '303 10CAP',
'c_pack_code' => 'PK0075',
'c_web_img_link' => ''
),
array(
'c_code' => '200005',
'itemname' => '3P 4TAB',
'c_pack_code' => '',
'c_web_img_link' => ''
)
);
$res1 = array();
$res2 = array();
foreach($arr as $val){
$res1['c_code'][] = $val['c_code'];
$res1['itemname'][] = $val['itemname'];
$res2['c_pack_code'][] = $val['c_pack_code'];
$res2['c_web_img_link'][] = $val['c_web_img_link'];
}
$out = array(array_merge($res1, $res2));
echo json_encode($out);

Most efficient way to replace empty values in an array

Is there a better way of doing this PHP code? What I'm doing is looping through the array and replacing the "title" field if it's blank.
if($result)
{
$count = 0;
foreach($result as $result_row)
{
if( !$result_row["title"] )
{
$result[$count]["title"] = "untitled";
}
$count++;
}
}
Where $result is an array with data like this:
Array
(
[0] => Array
(
[title] => sdsdsdsd
[body] => ssdsd
)
[1] => Array
(
[title] => sdssdsfds
[body] => sdsdsd
)
)
I'm not an experienced PHP developer, but I guess that the way I've proposed above isn't the most efficient?
Thanks
if($result) {
foreach($result as $index=>$result_row) {
if( !$result_row["title"] ) {
$result[$index]["title"] = "untitled";
}
}
}
You don't need to count it. It's efficient.
if ($result)
{
foreach($result as &$result_row)
{
if(!$result_row['title'])
{
$result_row['title'] = 'untitled';
}
}
}
Also, you may want to use something other than a boolean cast to check the existence of a title in case some young punk director releases a movie called 0.
You could do something like if (trim($result_row['title']) == '')
Mixing in a little more to #Luke's answer...
if($result) {
foreach($result as &$result_row) { // <--- Add & here
if($result_row['title'] == '') {
$result_row['title'] = 'untitled';
}
}
}
The key is the & before $result_row in the foreach statement. This make it a foreach by reference. Without that, the value of $result_row is a copy, not the original. Your loop will finish and do all the processing but it won't be kept.
The only way to get more efficient is to look at where the data comes from. If you're retrieving it from a database, could you potentially save each record with an "untitled" value as the default so you don't need to go back and put in the value later?
Another alternative could be json_encode + str_replace() and then json_decode():
$data = array
(
0 => array
(
'title' => '',
'body' => 'empty',
),
1 => array
(
'title' => 'set',
'body' => 'not-empty',
),
);
$data = json_encode($data); // [{"title":"","body":"empty"},{"title":"set","body":"not-empty"}]
$data = json_decode(str_replace('"title":""', '"title":"untitled"', $data), true);
As a one-liner:
$data = json_decode(str_replace('"title":""', '"title":"untitled"', json_encode($data)), true);
Output:
Array
(
[0] => Array
(
[title] => untitled
[body] => empty
)
[1] => Array
(
[title] => set
[body] => not-empty
)
)
I'm not sure if this is more efficient (I doubt it, but you can benchmark it), but at least it's a different way of doing the same and should work fine - you have to care about multi-dimensional arrays if you use the title index elsewhere thought.
Perhaps array_walk_recursive:
<?php
$myArr = array (array("title" => "sdsdsdsd", "body" => "ssdsd"),
array("title" => "", "body" => "sdsdsd") );
array_walk_recursive($myArr, "convertTitle");
var_dump($myArr);
function convertTitle(&$item, $key) {
if ($key=='title' && empty($item)) {$item = "untitled";}
}
?>
If you want sweet and short, try this one
$result = array(
array(
'title' => 'foo',
'body' => 'bar'
),
array(
'body' => 'baz'
),
array(
'body' => 'qux'
),
);
foreach($result as &$entry) if (empty($entry['title'])) {
$entry['title'] = 'no val';
}
var_dump($records);
the empty() will do the job, see the doc http://www.php.net/manual/en/function.empty.php

Categories