rearrange php multidimensional array according to id - arrays

-I cannot figure out how to regroup this array accourding to ids.
This array comes from a mysql table. the number 17 and 20 are foreign keys in the table.
$orginal_arr =
Array
(
[0] => Array
(
[id] => 17
[content] => string...?
)
[1] => Array
(
[id] => 20
[content] => hello
)
[2] => Array
(
[id] => 20
[content] => string...?
)
[3] => Array
(
[id] => 20
[content] => string...string...??
)
[4] => Array
(
[id] => 17
[content] => string...
)
[5] => Array
(
[id] => 17
[content] => string...
)
);
I want to convert the above $orginal_arr array to the following $desired_arr array.
$desired_arr = Array (
[0] => Array
(
[17] => Array
(
[0] => string...?
)
)
[1] => Array
(
[20] => Array
(
[0] => hello
[1] => string...?
[2] => string... string...??
)
)
[2] => Array
(
[17] => Array
(
[0] => string...
[1] => string...
)
)
);
so far I am trying the following approach:
function group_by_key($key, $data)
{
$result = array();
$j = 0;
foreach ($data as $val) {
if (array_key_exists($key, $val)) {
$result[$val[$key]][$j] = $val;
} else {
$result[""][] = $val;
}
$j++;
}
return $result;
}
$desired_arr = group_by_key("id", $orginal_arr);
$desired_arr2 = array();
foreach ($desired_arr as $index => $item) {
$desired_arr2 += $item;
}
echo "<pre>";
print_r($desired_arr2);
echo "</pre>";
the output:
Array
(
[0] => Array
(
[id] => 17
[content] => string...?
)
[4] => Array
(
[id] => 17
[content] => string...
)
[5] => Array
(
[id] => 17
[content] => string...
)
[1] => Array
(
[id] => 20
[content] => hello
)
[2] => Array
(
[id] => 20
[content] => string...?
)
[3] => Array
(
[id] => 20
[content] => string...string...??
)
)
- Thank you very much.

As I said in my comment, I'm not familiar to PHP syntax anymore so this will be pseudo code.
I would do it in 2 steps,
first I want this result
$temp_arr =
Array
(
[0] => Array
(
[id] => 17
[contents] => Array(
[0] => string...?
)
)
[1] => Array
(
[id] => 20
[contents] => Array(
[0] => hello
[1] => string...?
[2] => string...string...??
)
)
...
...
);
See, I kept the Object structure with id and contents (with a final S).
then it will be easier to check the id as it is directly accessible
$temp_array = Array();
foreach ($original_array as $element) {
$last = end($temp_array);
if ($last && $element->id == $last->id) {
// add to the last $temp_array element
$temp_array[count($temp_array)-1]->contents[] = $element->content;
}
else {
// create a new $temp_array element
$temp_array[] = Array(
"id" => $element->id,
"contents => Array(
$element->content
)
);
}
}
For the second step you just need to iterate the $temp_array and format as you like

here is another solution to this problem.
$desired_arr = array();
$prev_id = '';
$prev_key = null;
foreach ($orginal_arr as $key => $value) {
$this_id = $value['id'];
if ($this_id == $prev_id) {
array_push($desired_arr[$prev_key][$value['id']], $value['content']);
} else {
$desired_arr[$key][$value['id']] = (array)$value['content'];
$prev_key = $key;
}
$prev_id = $this_id;
}
$desired_arr = array_values($desired_arr);

Related

Extract specific values from stdClass Object

I have the following stdClass Object contained within $response:
stdClass Object ( [domain] => stdClass Object ( [id] => d1111111 [spamscore] => 75 [rejectscore] => 200 ) [domainalias] => Array ( ) [wildcard] => Array ( ) [catchall] => Array ( ) [forward] => Array ( ) [mailbox] => Array (
[0] => stdClass Object ( [highEmailNotification] => [id] => m1111111 [lastPasswordChange] => 2020-02-19T22:41:12+00:00 [local] => mailbox1 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )
[1] => stdClass Object ( [highEmailNotification] => [id] => m2222222 [lastPasswordChange] => 2020-02-17T15:46:21+00:00 [local] => mailbox2 [lowEmailNotification] => [quotaMB] => 10240 [receive] => 1 [rejectscore] => [send] => 1 [spamscore] => [usageMB] => 0 [enabled] => 1 )
[2] => stdClass Object ( [highEmailNotification] => [id] => m3333333 [lastPasswordChange] => 2020-02-19T15:00:36+00:00 [local] => mailbox3 [lowEmailNotification] => [quotaMB] => 1024 [receive] => 1 [rejectscore] => 0 [send] => 1 [spamscore] => 75 [usageMB] => 0 [enabled] => 1 ) ) [spamblacklist] => Array ( ) [spamwhitelist] => Array ( ) [responder] => Array ( ) [name] => domain.com )
I need to convert it into an array and extract particular values, i.e. [id] and [local] from it.
Speed is also an issue, as this array will grow to thousands of items, so if there is other, quicker way than 'foreach' it would be better.
I used some suggestions from here, such as:
$array = json_decode(json_encode($response), True);
foreach ($array as $var)
{
echo $var['id'] . ' - ' . $var['local'] . "<br>";
}
and got partial success with the results:
d1111111 -
-
-
-
-
i - i
(so it found the very first [id] value)
it however missed the most important values I am after.
What I need to get is:
m1111111 - mailbox1
m2222222 - mailbox2
m3333333 - mailbox3
Any suggestions are greatly appreciated.
The values you're trying to print is in a nested array within $response.
Try this.
$array = json_decode(json_encode($response['mailbox']), True);
foreach ($array as $var)
{
echo $var['id'] . ' - ' . $var['local'] . "<br>";
}

Reindex PHP Nested Array

After printing my $my_values['outer_group']['fieldset'] I'm getting the following output as per the data:
Array
(
[fieldset] => Array
(
[1] => Array
(
[title] => Dummy_Value1
[inner_group] => Array
(
[fieldset] => Array
(
[1] => Array
(
[id] => 11
[title] => Dummy_Value11
)
[2] => Array
(
[id] => 12
[title] => Dummy_Value12
)
[3] => Array
(
[id] => 13
[title] => Dummy_Value13
)
[actions] => Array
(
[add] => Add InnerGroup
[remove] => Remove InnerGroup
)
)
)
)
[2] => Array
(
[title] => Dummy_Value2
[inner_group] => Array
(
[fieldset] => Array
(
[1] => Array
(
[id] => 21
[title] => Dummy_Value21
)
[actions] => Array
(
[add] => Add InnerGroup
)
)
)
)
[actions] => Array
(
[add] => Add OuterGroup
[remove] => Remove OuterGroup
)
)
)
My requirement is to re-index the output data, hence I've performed the following code to re-index the same:
<?php
if (isset($my_values['outer_group']) && !empty($my_values['outer_group'])) {
$outer_types = $my_values['outer_group']['fieldset'];
$inner = [];
foreach ($outer_types as $outer_key => $outer_value) {
if (is_numeric($outer_key)) {
if (isset($outer_value['inner_group']['fieldset'])) {
foreach ($outer_value['inner_group']['fieldset'] as $k => $v) {
if (is_numeric($k)) {
$inner[] = [
'id' => $v['id'],
'title' => !empty($v['title']) ? $token->replace($v['title']) : NULL,
];
}
}
}
$my_values['outer'][$outer_key] = [
'title' => !empty($outer_value['title']) ? $token->replace($outer_value['title']) : NULL,
'inner' => $inner,
];
}
}
}
As per the output its getting re-indexed but with some errors in data. I'm getting trouble while populating the [inner] data, following is the output for the same:
Array
(
[0] => Array
(
[title] => Dummy_Value1
[inner] => Array
(
[0] => Array
(
[id] => 11
[title] => Dummy_Value11
)
[1] => Array
(
[id] => 12
[title] => Dummy_Value12
)
[2] => Array
(
[id] => 13
[title] => Dummy_Value13
)
)
)
[1] => Array
(
[title] => Dummy_Value2
[inner] => Array
(
[0] => Array
(
[id] => 11
[title] => Dummy_Value11
)
[1] => Array
(
[id] => 12
[title] => Dummy_Value12
)
[2] => Array
(
[id] => 13
[title] => Dummy_Value13
)
[3] => Array
(
[id] => 21
[title] => Dummy_Value21
)
)
)
)
Whereas, it should be:
Array
(
[0] => Array
(
[title] => Dummy_Value1
[inner] => Array
(
[0] => Array
(
[id] => 11
[title] => Dummy_Value11
)
[1] => Array
(
[id] => 12
[title] => Dummy_Value12
)
[2] => Array
(
[id] => 13
[title] => Dummy_Value13
)
)
)
[1] => Array
(
[title] => Dummy_Value2
[inner] => Array
(
[0] => Array
(
[id] => 21
[title] => Dummy_Value21
)
)
)
)
$inner = []; needs to be within the foreach loop so that it is empty before building each internal element.
Untested - but as follows:
<?php
if (isset($my_values['outer_group']) && !empty($my_values['outer_group'])) {
$outer_types = $my_values['outer_group']['fieldset'];
foreach ($outer_types as $outer_key => $outer_value) {
$inner = [];
if (is_numeric($outer_key)) {
if (isset($outer_value['inner_group']['fieldset'])) {
foreach ($outer_value['inner_group']['fieldset'] as $k => $v) {
if (is_numeric($k)) {
$inner[] = [
'id' => $v['id'],
'title' => !empty($v['title']) ? $token->replace($v['title']) : NULL,
];
}
}
}
$my_values['outer'][$outer_key] = [
'title' => !empty($outer_value['title']) ? $token->replace($outer_value['title']) : NULL,
'inner' => $inner,
];
}
}
}

How to add new array in to existing array dynamically using session in codeigniter

i want to store multiple array in same session on every function call .. my function is given below.
function store_item($param='')
{
$count = count($this->session->userdata('items_array'));
echo $count;
$count++;
$item_id = $this->input->post('product_id');
$data[][$count] = $this->Quotation_model->get_data_single($item_id);
$this->session->set_userdata('items_array',$data);
}
i want this result
Array ( [0] => Array ( [0] => Array ( [name] => Check [category_id] => 1 [supplier_id] => ) ) Array ( [1] => Array ( [name] => Check [category_id] => 1 [supplier_id] => ) ) Array ( [2] => Array ( [name] => Check [category_id] => 1 [supplier_id] => ) ))
Try this you are overwriting session array each time
$data = $this->session->userdata('items_array');
echo $count;
$count++;
$item_id = $this->input->post('product_id');
$data[] = $this->Quotation_model->get_data_single($item_id);
$this->session->set_userdata('items_array',$data);
Here you are first get session details to variable then add new item details to same variable to set session again with new data

Split Two Dimensional Array into n more based on key value

i've been busting my head over this array:
Array (
[invoicenr] => Array (
[0] => 1234
[1] => 1234
[2] => 1234
[3] => 4321
[4] => 3214
)
[invoicedate] => Array (
[0] => 17.07.2017.
[1] => 17.07.2017.
[2] => 17.07.2017.
[3] => 11.07.2017.
[4] => 11.07.2017. )
[amount] => Array (
[0] => 10
[1] => 1
[2] => 23
[3] => 10
[4] => 1 )
[cause] => Array (
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 1 )
)
I'm trying to split array above based on 1st level key "invoicenr" value, but without luck so far.
I'm expecting result:
Array (
[invoicenr] => Array (
[0] => 1234
[1] => 1234
[2] => 1234)
[invoicedate] => Array (
[0] => 17.07.2017.
[1] => 17.07.2017.
[2] => 17.07.2017.)
[amount] => Array (
[0] => 10
[1] => 1
[2] => 23)
[cause] => Array (
[0] => 1
[1] => 1
[2] => 1)
)
Array (
[invoicenr] => Array (
[0] => 4321 )
[invoicedate] => Array (
[0] => 11.07.2017. )
[amount] => Array (
[0] => 10)
[cause] => Array (
[0] => 1 )
)
Array (
[invoicenr] => Array (
[0] => 3214 )
[invoicedate] => Array (
[0] => 11.07.2017. )
[amount] => Array (
[0] => 1)
[cause] => Array (
[0] => 1 )
)
I want to know if this is possible and how, or i need to rewrite array first?
Thank you all in advance, i'm new into coding and struggling to learn so far. :)
Please post the code you attempted to solve the problem with.
I believe you will need a counter (i) to go through invoicenr and a temporary variable that remembers the last value (Array[i]) and compares it with the next value in the array of invoicenr. If the value is the same you keep going, and if it is different you print out all the other arrays[i].
i've finnaly did it, but i think my way is too primitive. Here is what i did:
//Count number of rows in initial array
$rows = count(array_filter($_POST['invoicenr']));
//Crete unique array that contains only $_POST['invoicenr'] which i can count later
$uniquearray = array();
for ($row = 0; $row < $rows; $row++) {
$uniquearray[] = $_POST['invoicenr'][$row] ;
}
//return unique keys only
$invoicenrunique=array_keys(array_flip($uniquearray));
//count number of rows in unique array
$invoicenruniquecount=count(array_keys(array_flip($uniquearray)));
//do magic, this splits main array into n smaller arrays based on $_POST['invoicenr']
for($uniquerow = 0; $uniquerow < $invoicenruniquecount; $uniquerow++) {
$testarray = array();
for ($row = 0; $row < $rows; $row++) {
if($_POST['invoicenr'][$row]==$invoicenrunique[$uniquerow]){
$testarray[$row]['invoicenr']=$_POST['invoicenr'][$row];
$testarray[$row]['invoicedate']=$_POST['invoicedate'][$row];
$testarray[$row]['amount']=$_POST['amount'][$row];
$testarray[$row]['cause']=$_POST['cause'][$row];
}
}
print_r(array_values($testarray));
echo "<br>";
}
Do you have any suggestions on how to improve my solution?
Best regards!

How to perform array manipulation

I have an array like this from cdbcommand select query. (Using Yii)
Array(
[0] => Array(
[0] => Array
(
[id] => 21
)
[1] => Array
(
[id] => 91
)
[2] => Array
(
[id] => 125
)
)
[1] => Array
(
[0] => Array
(
[id] => 15
)
)
)
I want final array like array(21, 91, 125, 15)
How can I do this?
$output=array();
foreach($result as $row){
foreach($row as $id_container){
$output[]=$id_container["id"];
}
}
This will give you what you need, if array structure is dependable - then it wont work.
try this
$newArray=array();
foreach($result as $value)
{
array_merge($newArray,array_values($value));
}

Resources