Multidimensional array in php to save mysqli output - php

Here is a piece of my code:
if($all_pages)
foreach ($all_pages as $page)
{
$all_hokms = $mysqli->query("SELECT * FROM qm_hokm WHERE page_id = ".$page['page_id']."");
if($all_hokms)
foreach ($all_hokms as $hokm)
{
$one_page_ahkams[] = array(
'hokm_id_inPage' => $hokm['hokm_id_inPage'],
'type' => $page['type'],
);
}
else
$one_page_ahkams[] = array();
$all_pages_data[] = array(
'page_id' => $page['page_id'],
'done' => $page['done'],
'checked' => $page['checked'],
'ahkams' => array($one_page_ahkams), //Here Is the PROBLEM : (((
);
}
else
$all_pages_data[] = array();
echo json_encode($all_pages_data);
As you see, I want to send multidimensial array() in a json format (from server to client), but how can correct the insertion of an array in an other, I mean that I need to add $one_page_ahkams array in $all_pages_data one, any ideas

$one_page_ahkams = array();
$all_pages_data[] = array(
'page_id' => $page['page_id'],
'done' => $page['done'],
'checked' => $page['checked'],
'ahkams' => array($one_page_ahkams);//this comma (,) causes the problem i guess**
);
An other way to do it :
$all_pages_data[] = array(
'page_id' => $page['page_id'],
'done' => $page['done'],
'checked' => $page['checked'],
'ahkams' => array(['one_page_ahkams']=>$one_page_ahkams);
);

Just put that: 'ahkams' => array($one_page_ahkams), but check the content of $one_page_ahkams

Related

How to use a while loop result within three dimensional array in php?

I would like to pass a while loop result as a value to three dimensional array,i have tried but i couldn't get it.I am trying to solve this from few days.Any suggestions or answers are appreciated.Thank you
$messages = array(
'sender' => "akhil",
'messages' => array(
//////////////while loop starts
while($i < $data){
array(
'number' =>$data[$i],//////here i want to pass the while loop
variable
'text' => rawurlencode('Hello,.........')
)
$i++;
}
/////////////while loop ends
)
);
///the would like to get the below result
$messages = array(
'sender' => "akhil",
'messages' => array(
array(
'number' => 918xxxxxx,
'text' => rawurlencode('Hello,------')
),
array(
'number' => 9196xxxxxx,
'text' => rawurlencode('Hello,----')
)
), array(
'number' => 919xxxxx,
'text' => rawurlencode('Hello,----')
)
)
);
You just need to create the array outside the while loop and then push values into it inside the loop. Your code is almost there...
$messages = array('sender' => "akhil",
'messages' => array()
);
while ($i < count($data)) {
$messages['messages'][] = array('number' => $data[$i],
'text' => rawurlencode('Hello,.........'));
$i++;
}
Demo on 3v4l.org
What you are looking for is called an Anonymous function.
You can achieve your expected behavior by doing this:
'messages' => (function(){
$res = [];
while($i < $data){
$res[] = [
'number' =>$data[$i],//////here i want to pass the while loop variable
'text' => rawurlencode('Hello,.........')
];
$i++;
}
return $res;
})(),
...
I do not know the exact structure of your data, but I would swap the while for an array_map(). It would look like this:
'messages' => array_map(function($d){
return [
'number' =>$d,
'text' => rawurlencode('Hello,.........')
]
},$data),
...
Hohpe that helps,

assign array data in PHP

I did search for this but may be my search sucks. So posting it here..my code below
while( $row = mysqli_fetch_array($queryRecords) ) {
$data['data'][] = array(
'student_name' => $row['name'],
'totalmark' => $row['totalmark'],
$marksheet = calculatepercent(totalmark),
'resultdate' => $row['resultdate'].$marksheet,
'ID' => $row['ID']
);
Here I call function calculatepercent(totalmark) so that the function returns a value and store that in $marksheet. But my problem is this does not work i.e I cannot store the result of calculatepercent(totalmark) because I cannot access 'totalmark'
Forget performance for a minute but how do you make this work? (If you have tips for performance that's a bonus too! ) - Thanks Coders!
RR
Try like this.Send $row['totalmark'] to the calculatepercent() function.
while( $row = mysqli_fetch_array($queryRecords) ) {
$data['data'][] = array(
'student_name' => $row['name'],
'totalmark' => $row['totalmark'],
$marksheet => calculatepercent($row['totalmark']),
'resultdate' => $row['resultdate'].$marksheet,
'ID' => $row['ID']
);
I guess I was more desperate than any one else to get an answer! So after trying many things I got it working and sharing it here for any one else
while( $row = mysqli_fetch_array($queryRecords) ) {
$marksheet = calculatepercent($row['totalmark'];
$data['data'][] = array(
'student_name' => $row['name'],
'totalmark' => $row['totalmark'],
//move the fn 'calculatepercent' outside while loop $marksheet => //calculatepercent($row['totalmark']),
'resultdate' => $row['resultdate'].$marksheet,
'ID' => $row['ID']
);

sorting a multi dimensional array in php

I have an array of arrays, as such
$statuses = array(
[0] => array('id'=>10, 'status' => 'active'),
[1] => array('id'=>11, 'status' => 'closed'),
[2] => array('id'=>12, 'status' => 'active'),
[3] => array('id'=>13, 'status' => 'stopped'),
)
I want to be able to make a new array of arrays and each of those sub arrays would contain the elements based on if they had the same status.
The trick here is, I do not want to do a case check based on hard coded status names as they can be random. I want to basically do a dynamic comparison, and say "if you are unique, then create a new array and stick yourself in there, if an array already exists with the same status than stick me in there instead". A sample result could look something like this.
Ive really had a challenge with this because the only way I can think to do it is check every single element against every other single element, and if unique than create a new array. This gets out of control fast if the original array is larger than 100. There must be some built in functions that can make this efficient.
<?php
$sortedArray = array(
['active'] => array(
array(
'id' => 10,
'status' => 'active'
),
array(
'id' => 12,
'status' => 'active'
)
),
['closed'] => array(
array(
'id' => 11,
'status' => 'active'
)
),
['stopped'] => array(
array(
'id' => 13,
'status' => 'active'
)
),
)
$SortedArray = array();
$SortedArray['active'] = array();
$SortedArray['closed'] = array();
$SortedArray['stopped'] = array();
foreach($statuses as $Curr) {
if ($Curr['status'] == 'active') { $SortedArray['active'][] = $Curr; }
if ($Curr['status'] == 'closed') { $SortedArray['closed'][] = $Curr; }
if ($Curr['status'] == 'stopped') { $SortedArray['stopped'][] = $Curr; }
}
You can also do it with functional way though it's pretty the same like Marc said.
$sorted = array_reduce($statuses, function($carry, $status) {
$carry[$status['status']][] = $status;
return $carry;
}, []);

how to format json with array of json

I want output in json like this
response:{url="www.google.com/raj.png", size=12.344KB},{url="www.google.com/raj2.png", size=12.344KB},{url="www.google.com/raj4.png", size=12.344KB}
But currently i am getting
"url=> www.google.com/img1.png size => 12.344 KB,url=> www.google.com/img2.png size => 12.344 KB"
//Using some loop here
{
$response[] = array('url' => 'url_value','size' => 'file_size');
}
//without loop hardcoded values:
$response = array ( array('url' => "www.google.com/raj.png",'size' => "12.344KB"),
array('url' => "www.google.com/img2.png",'size' => "10.344KB") );
return json_encode($response);
$out= Array(
Array('url'=>'www.goog', 'size'=>'12KB'),
Array('url'=>'moogle', 'size'=>'13KB')
);
echo Json_encode($out);
Not sure how you are formatting your array, but if you define it like this it should do the trick:
$response_array = array(
'response' => array(
array(
'url' => 'www.google.com/raj.png',
'size' => '12.344KB',
),
array(
'url' => 'www.google.com/raj.png',
'size' => '12.344KB',
),
array(
'url' => 'www.google.com/raj.png',
'size' => '12.344KB',
),
),
);
$respose_json = json_encode($response_array);
echo($response_json);
For looping through some results, try something like this:
$response_array = array('response' => array());
foreach($result_set as $result_item) {
$response_item = array();
$response_item['url'] = $result_item['url'];
$response_item['size'] = $result_item['size'];
$response_array['response'][] = $response_item;
}
$respose_json = json_encode($response_array);
echo($response_json);
With the $result_set above being whatever data you've pulled from a DB, server, etc.

Array - custom foreach function

I have an array in this form:
$data = array(
array(
'id' => '1',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'bar',
'bar' => 'foo',
'page' => 'front',
),
array(
'id' => 'different,
'bar' => 'bar',
'page' => 'back',
),
array(
'id' => 'another',
'title' => __("Custom CSS",'solidstyle_admin'),
'foo' => 'bar',
'page' => 'back',
),
);
And I want to list all ids grouped by pages and saved as variables, so if the above array is an input then output will look just like this one:
$front = array('1','bar');
$back = array('different','another');
//$data['page'] = array($id1, $id2, (...));
I was trying to do that using foreach and this is how it starts:
function my_output() {
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
}
return $output;
}
I was trying multiple foreach loops, and the best result I got was:
front = 1
front = bar
back = different
back = another
But I have absolutely no idea how to achieve what I want to do, I don't want anyone to do my job, just any hints? Keep in mind I'm a bit new to PHP and I don't know too much about arrays.
Thank you!
Sounds like you want:
$ids = array();
foreach ($data as $page) {
$pageName = $page['page'];
// create an empty array for your IDs
if (!isset($ids[$pageName])) {
$ids[$pageName] = array();
}
// add to the array of IDs
$ids[$pageName][] = $page['id'];
}
var_dump($ids); // array('front' => array('1', 'bar'), ...
Stick with the loop idea and do a conditional check.
function my_output() {
$front = array();
$back = array();
foreach($data as $something) {
$id = $something['id'];
$page = $something['page'];
if ($page === 'front') {
$front[] = $id;
} else if ($page === 'back') {
$back[] = $id;
}
}
// Not sure what you want to return here, but you could return an array of pages
$output = array('front' => $front, 'back' => $back);
return $output;
}
This will return something similar to:
$output = array(
'front' => array(
0 => '1',
1 => 'bar',
),
'back' => array(
0 => 'something',
1 => 'another',
)
)
Edit: Keep in mind that my answer only accounts for the two pages you listed in your answer. If you have more pages you can also use what cbuckley's answer showed.

Categories