Array into array using array_push key issue - php

I'm getting confused about how to insert array into array and give it a key name. Not number!.
I have the main array, which contains info about customer. the sub array should be called ["verlauf"].
The ["verlauf"] array conatins multiple arrays ( as same as db row count ). the main idea is that the sub array should be having the key name ["verlauf"]. in my code im getting the [0] as key.
Current array output:
array(19) {
["id"]=> string(1) "1"
["name"]=> string(11) "qwert zuiop"
["email"]=> string(23) "xy#gmail.com"
["phn_num"]=> string(12) "123456789"
[0]=> array(1) {
[0]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "22:25"
["status"]=> string(1) "0"
["info"]=> string(34) "some info"
}
[1]=> array(4) {
["datum"]=> string(10) "30.07.2020"
["uhr_zeit"]=> string(5) "23:25"
["status"]=> string(1) "1"
["info"]=> string(34) "some info"
}
}
}
what i want is that the [0] on line 6 in the above example to be ["verlauf"]
My PHP:
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
array_push($returnArray, $verlaufArray);
Please note that $returnArray is the "main array".

You can simply do that by using associate array-
Your PHP code -
while ($row = mysqli_fetch_array($result)) {
$verlaufArray[] = array(
"datum" => $row['datum'],
"uhr_zeit" => $row['uhr_zeit'],
"status" => $row['status'],
"info" => $row['info']);
}
$returnArray['verlauf'] = $verlaufArray;

There's no need to complicate things so much. It looks like you need just one line of code.
$returnArray['verlauf'] = $result->fetch_all(MYSQLI_ASSOC);
There's no need for the while loop if the structure remains the same. fetch_all(MYSQLI_ASSOC) will give you an array containing associative results from your query.

Related

addition of strings inside an multidimensional array - php

I have an array like this. Each array is having a user ID with scores populated dynamically. I want to add all the strings inside the array and have the key as userID
array(3) {
[13702]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "9"
[2]=> .....
..... more elements
}
[13703]=>
array(2) {
[0]=>
string(1) "7"
[1]=>
string(1) "6"
.....
..... more elements
}
[13774]=>
array(1) {
[0]=>
string(1) "7"
.....
..... more elements
}
}
I want to make it like below
array(
'13702'=> 13,//this is the sum of strings inside it
'13703'=> 13,
'13774'=> 7,
);
Please help
No need for array reduce, a simple array_map applying array_sum on each sub array should suffice:
$result = array_map('array_sum', $array);

How to loop through array of multiple arrays in php

I am trying to loop through array of arrays in php. Usually get stalked with complex array sometimes but I need your kind assistance with this.
var_dump($array) produced the array below:
$arrayVal = array(6) {
["item_id"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
["request_explanation"]=>
array(2) {
[0]=>
string(7) "Welcome"
[1]=>
string(11) "Hello World"
}
["quantity"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "4"
}
["unit_cost"]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "3"
}
["total_cost"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["supporting_document"]=>
string(0) ""
}
My database table:
I want to be able to save each of the value in that array into the table above. Thanks for helping me.
Use the indexes of one of the sub-arrays to access all the other sub-arrays:
foreach ($array['item_id'] as $i => $item_id) {
$request_explanation = $array['request_explanation'][$i];
$quantity = $array['quantity'][$i];
// repeat this for all the columns
// Now you can insert all these variables into the database
}
Use a loop to build 2 separate arrays:
foreach($array['ExpensesList'] as $index => $val){
$array1[$index] = $array['ExpensesList'][$index][0];
$array2[$index] = $array['ExpensesList'][$index][1];
}
Then insert each array into your database individually.
This will not work if any sub array contains an index at 2, so this is explicitly for the example structure you provided.

PHP Get Value from Array with Value of Key

following problem: I want to build a mysql based language system.
To decrease loading time and increase performance I thought it would be the best, to first fetch all Language phrases into an array (which happens with mysqli fetch array). Then, if a language term is required, calling a function with the array as global variable.
My function for the array:
$sql = $db->query('SELECT * FROM lang_phrases WHERE phraseLanguageId = 1');
$phrases = array();
while($row = $sql->fetch_array()) {
$phrases[] = $row;
}
Now I've got this array:
array(2) {
[0]=> array(8) {
[0]=> string(1) "1"
["phraseId"]=> string(1) "1"
[1]=> string(1) "1"
["phraseLanguageId"]=> string(1) "1"
[2]=> string(4) "HOME"
["phraseKey"]=> string(4) "HOME"
[3]=> string(10) "Homepage"
["phraseContent"]=> string(10) "Homepage"
}
[1]=> array(8) {
[0]=> string(1) "2"
["phraseId"]=> string(1) "2"
[1]=> string(1) "1"
["phraseLanguageId"]=> string(1) "1"
[2]=> string(4) "BACK"
["phraseKey"]=> string(4) "BACK"
[3]=> string(6) "Back"
["phraseContent"]=> string(6) "Back"
}
}
And thats my function:
function l($key) {
global $phrases;
return PLACEHOLDER;
}
I wonder, how can I now search the array for "phraseKey" $key from the function and get the value?
Do you have any hints? Or shall I simply select each phrase with each one query (performance problems with 100 quers per load?!)?
Cheers and Thanks!
That's a bad structure. Why not key your array with the phrase ID and the language? e.g.
$translations = array(
'HOME' => array(
'english' => 'Home',
'french' => 'Maison',
'german' => 'Haus"
etc...
This eliminates the need for ANY searching. You just look up directly by language/phrase ID.
May I suggest to retrive the phrases with
while($row = $sql->fetch_array()) {
$phrases[$row['phraseKey']] = $row;
}
Then in your function l($key) you can search them with
$t = isset($phrases[$key]) ? $phrases[$key] : null

Convert array with steps of two

Say I have an array that looks like this:
array(100) {
[0]=>
array(4) {
["player_id"]=>
string(2) "jk"
["date"]=>
string(10) "2012-11-07"
["hits"]=>
string(4) "1000"
}
[1]=>
array(4) {
["player_id"]=>
string(2) "jk"
["date"]=>
string(10) "2012-11-14"
["hits"]=>
string(4) "2000"
}
[2]=>
array(4) {
["player_id"]=>
string(2) "mc"
["date"]=>
string(10) "2012-11-14"
["hits"]=>
string(4) "1500"
}
[3]=>
array(4) {
["player_id"]=>
string(2) "mc"
["date"]=>
string(10) "2012-11-07"
["hits"]=>
string(4) "2300"
}
...
And this continues. So, basically I have several players and for each player I have two dates. I would like to end up having an array like this:
array(100) {
["jk"]=>
array(2) {
["hits_today"]=>
string(4) "1000"
["hits_difference"]=>
string(5) "-1000"
}
["mc"]=>
array(2) {
["hits_today"]=>
string(4) "1500"
["hits_difference"]=>
string(4) "-800"
}
..
Basically I want to process the first array knowing that for each player I (might) have two values, and create an array of arrays that as keys uses the player_id and as components with the difference between those two values, and the value of today.
My concerns are:
What is the best way to process the first array?
How would I manage if the value of today doesn't exist, or the value of tomorrow doesn't? How can I control that while processing the array?
If this comes from a query I would do this instead:
SELECT player_id,
SUM(IF(`date`='$yesterday', hits, 0)) AS hits_yesterday,
SUM(IF(`date`='$today', hits, 0)) AS hits_today
FROM ...
GROUP BY player_id
I needed to preserve the date in the output array to determine if the current date being calculated was > or < the date already on hand, but this is the solution I came up with:
$array = array(
array("player_id" => "jk", "date" => "2012-11-07", "hits" => "1000"),
array("player_id" => "jk", "date" => "2012-11-14", "hits" => "2000"),
array("player_id" => "mc", "date" => "2012-11-14", "hits" => "1500"),
array("player_id" => "mc", "date" => "2012-11-07", "hits" => "2300")
);
$output = array();
foreach($array as $k=>$v){
if(!isset($output[$v['player_id']])){
$output[$v['player_id']]['hits_today'] = $v['hits'];
$output[$v['player_id']]['hits_difference'] = 0;
$output[$v['player_id']]['date'] = $v['date'];
}elseif($v['date'] < $output[$v['player_id']]['date']){
$output[$v['player_id']]['hits_difference'] = $output[$v['player_id']]['hits_today'] - $v['hits'];
}elseif($v['date'] > $output[$v['player_id']]['date']){
$output[$v['player_id']]['hits_difference'] = $output[$v['player_id']]['hits_today'] - $v['hits'];
$output[$v['player_id']]['hits_today'] = $v['hits'];
$output[$v['player_id']]['date'] = $v['date'];
}
}
echo '<pre>';
print_r($output);
echo '</pre>';
?>

Sort an array from another array values in PHP

I got an $actions array, and $actions_used array.
$actions_used looks like this:
array(1) {
[2]=>
string(1) "18"
[5]=>
string(1) "33"
}
$actions looks like this:
array(3) {
[1]=>
string(9) "Withdraw"
[2]=>
string(13) "Deposit"
[5]=>
string(10) "Blabla"
}
I would like to sort $actions based on the value that is in $actions_used.
The correct output would be for $actions:
array(3) {
[5]=>
string(9) "Blabla"
[2]=>
string(13) "Deposit"
[1]=>
string(10) "Withdraw"
}
Why? Because array key 5, "Blabla" has the biggest value "33" and then comes array key "2" which has value 18 and then at last comes array key 1, "Withdraw" which have 0 (no value)
How can this be done?
This should do the trick.
$sorted_actions = array();
asort($actions_used);
foreach($actions_used AS $key => $amount) {
$sorted_actions[] = array('amount' => $amount, 'action' => $actions[$key]);
unset($actions[$key]);
}
$sorted_actions = $sorted_actions + $actions;
How would something like this work?
arsort($action_used);
foreach ($action_used as $k => $v) {
$newArray[$k] = $actions[$k];
unset($action_used[$k];
}
$newArray = array_merge($newArray, $action_used);
I think you could sort the second array with uksort and actually compare the values from the first array in the custom comparer
e.g.:
uksort($arr2, function($i1, $i2) {
return $arr1[$i1] - $arr1[$i2];
});

Categories