reformat existing array to group items together - php

I have the following array:
Array
(
[0] => Array
(
[name] => bss2
[label] => front
[text] => just a testing item
)
[1] => Array
(
[name] => bss3
[label] => front top
[text] => front top testing item
)
[2] => Array
(
[name] => J334
[label] => back top
[text] => masking test back top
)
[3] => Array
(
[name] => J3366
[label] => back
[text] => back non mask test
)
)
What i would like to accomplish is to check to see if label = front then group the ones with front together and same with back all in one big array to have it looks like so:
[approval] => Array(
[0] => Array(
[name] => front
[prev] => Array(
[0]=>Array(
[name] => bss2
)
[1]=>Array(
[name] => bss2
)
)
)
[1] => Array(
[name] => back
[prev] => Array(
[0]=>Array(
[name] => J334
)
[1]=>Array(
[name] => J3366
)
)
)
)
so far I dont have much and am stuck but this is my code
foreach($info as $data) {
if(strtolower(strpos($data['label'], "front") !==false)) {
} else {
}
}
Iv also tried using array_chunk which works great but what would happen if there are 3 elements that need to be grouped or 4
array_chunk($info, 2);
or what would happen if the order is different where one is front and second is back it will then combine the front and back together.
Any help is greatly appreciated thank you.

This should do it, assuming the only choices are front and back.
$result = array(array('name' => 'front', 'prev' => array()),
array('name' => 'back', 'prev' => array()));
foreach ($info as $data) {
$i = (strpos(strtolower($data['label']), "front") !== false)
$result[$i]['prev'][] = array('name' => $data['name'];
}
$newinfo = array('approval' => $result;

It's not clear to me exactly what you're after... If it's just front and back or if you want top and any other group as well?
Methods
Anyway, here are a few options that should cover most cases.
Front and Back only
This is the simplest and will just check for front and back. If it finds them then it will ad to front and back in $newArray as is required.
$newArray = array(array('front'), array('back')); //The new reformatted array
for($i = 0; $i < count($initialArray); $i++){
if(strpos($initialArray[$i]['label'], 'front') !== FALSE){//Check if group is front
$newArray[0]['prev'][] = array('name'=>$initialArray[$i]['name']); //Add to front
}
if(strpos($initialArray[$i]['label'], 'back') !== FALSE){//Check if group is back
$newArray[1]['prev'][] = array('name'=>$initialArray[$i]['name']); //Add to back
}
}
Pre-defined groups
This one's a bit more complex and will search for all groups found in $groups. The code below shows only front and back but you could also add in, for example, top or any others.
$groups = array('front', 'back'); //Groups to search for e.g. front, back, and top
$newArray = array(); //The new reformatted array
for($i = 0; $i < count($initialArray); $i++){
foreach($groups as $group){
if(strpos($initialArray[$i]['label'], $group) !== FALSE){//Check if group is in label
$groupKey = array_search($group, $groups); //Search for the key in $groups
$newArray[$groupKey]['prev'][] = array('name'=>$initialArray[$i]['name']); //Add to relevant group
}
}
}
Automated
This is the most advanced code which will automatically search and add new groups as they are found in the array. It's also fully automated so all you have to do is point it at the correct array.
$groups = array(); //Index of groups like: top, front, and back
$newArray = array(); //The new reformatted array
for($i = 0; $i < count($initialArray); $i++){
$possibleGroups = explode(' ', strtolower($initialArray[$i]['label'])); //Get list of applicable groups
foreach($possibleGroups as $newGroup){
if(!in_array($newGroup, $groups)){ //If group doesn't already exist in $groups add it
$groups[] = $newGroup;
$newArray[] = array('name'=>$newGroup, 'prev'=>array());
}
$groupKey = array_search($newGroup, $groups); //Search for the key in $groups
$newArray[$groupKey]['prev'][] = array('name'=>$initialArray[$i]['name']); //Add to relevant group
}
}
Test array
The above codes have been tested with the following array...
$initialArray = array(
array(
'name' =>'bss2',
'label'=>'front',
'text' =>'sometihng...'
),
array(
'name' =>'bss3',
'label'=>'front top',
'text' =>'sometihng...'
),
array(
'name' =>'j334',
'label'=>'back top',
'text' =>'sometihng...'
),
array(
'name' =>'j3366',
'label'=>'back',
'text' =>'sometihng...'
)
);
Example Output
Output of the third method (automated) using the test array above.
array (
0 =>
array (
'name' => 'front',
'prev' =>
array (
0 =>
array (
'name' => 'bss2',
),
1 =>
array (
'name' => 'bss3',
),
),
),
1 =>
array (
'name' => 'top',
'prev' =>
array (
0 =>
array (
'name' => 'bss3',
),
1 =>
array (
'name' => 'j334',
),
),
),
2 =>
array (
'name' => 'back',
'prev' =>
array (
0 =>
array (
'name' => 'j334',
),
1 =>
array (
'name' => 'j3366',
),
),
),
)

Related

Send a variable number of POST array variables to their own array

I've got a dynamic form that allows a user to create as many form elements as they need -- then submit them. For this, I have prepared the input names as arrays like
<input name="title[]" ...
and posting them gives me output like
Array
(
[day] => 0
[project_id] => 5
[submit] => publish
[id] => Array
(
[0] => 4
[1] => 5
)
[title] => Array
(
[0] => Step 1
[1] => Step 2
)
[max_vol] => Array
(
[0] => 2
[1] => 3
)
[description] => Array
(
[0] => df dofi dofidfoi
[1] => dfvpdofvdpfo osd pod
)
)
I've created something that allows me to just grab the post arrays like so
foreach( $_POST as $post_key ) {
// ignore non-array post variables
if( is_array( $post_key ) ) {
foreach( $post_key as $form_value ) {
echo "$form_value\n";
}
}
}
/* ouputs...
4
5
Step 1
Step 2
2
3
df dofi dofidfoi
dfvpdofvdpfo osd pod
*/
which nicely sorts the non-arrays from the arrays, but I can't figure out how to take this variable number of created form elements and prepare them into an array variable that looks something like...
Array
(
[0] => Array
(
'id' => 4, 'title' => 'Step 1', 'max_vol' => '2', 'description' => 'df dofi dofidfoi'
),
[1] => Array
(
'id' => 5, 'title' => 'Step 2', 'max_vol' => '3', 'description' => 'dfvpdofvdpfo osd pod'
),
// could be more or less elements...
);
(I will be eventually passing these arrays to a MySQL query builder function).
Thanks.
How about creating a variable that is outside the scope of the foreach loop
$results = array();
foreach( $_POST as $post_key=>$post_value ) {
// ignore non-array post variables
if( is_array( $post_value ) ) {
foreach( $post_value as $form_key=>$form_value ) {
if (!isset($results[$form_key]))
{
$results[$form_key] = array();
}
$results[$form_key][$post_key] = $form_value;
}
}
}
// results is your array variable
print_r($results);
Iterate over some significant $_POST-array key, for example - id and get the values from other $_POST-arrays with the same index:
$values = array();
foreach ($_POST['id'] as $k => $v) {
$values[] = array(
'id' => $v,
'title' => $_POST['title'][$k],
'max_vol' => $_POST['max_vol'][$k],
'description' => $_POST['description'][$k],
);
}
print_r($values);

Append a new array to an existing array

I am using Codeigniter Sessions to build a "Betslip".
I am adding the team name and odds to the bet slip and then plan to loop through each "bet" element to create a betslip.
The ideal array needs to look like :
[betslip] => Array
(
[bet] => Array
(
[team] => Rayo Vallecano
[odds] => 67/100
)
[bet] => Array
(
[team] => Elche
[odds] => 1/100
)
)
However in my code, I just seem to be overwriting what is already there.
My current PHP code is as follows :
// Get Team Name
$teamname = $this->uri->segment(3);
// Get Odds
$odds1 = $this->uri->segment(4);
$odds2 = $this->uri->segment(5);
$odds = $odds1;
$odds .= "/";
$odds .= $odds2;
// Build An array titled Bet
$bet = array(
'bet' => array(
'team' => urldecode($teamname),
'odds' => $odds
)
);
$betslip = $this->session->userdata('betslip');
// Create The Betslip For The First Time...
if(empty($betslip))
{
$this->session->set_userdata('betslip', $bet);
}
else
{
// Add To The Betslip Array...
$betslip['bet'] = array(
'team' => urldecode($teamname),
'odds' => $odds
);
$this->session->set_userdata('betslip', $betslip);
}
How do I just append a bet to the existing bet slip array?
Is it possible to have multiple array keys with the same name too?
Thanks in advance..
This is not an ideal array
[betslip] => Array
(
[bet] => Array
(
[team] => Rayo Vallecano
[odds] => 67/100
)
[bet] => Array
(
[team] => Elche
[odds] => 1/100
)
)
it should be like
[betslip] => Array
(
[0] => Array
(
[team] => Rayo Vallecano
[odds] => 67/100
)
[1] => Array
(
[team] => Elche
[odds] => 1/100
)
)
<?php
$item = array();
$item2 = array(
'team' => 1,
'odds' => "1/100"
);
for ($x = 0; $x <= 10; $x++) {
$item[] = $item2;
}
print_r($item);
?>

How to add new index and value from another array in PHP?

I need your help with my problem. My problem is I have 2 arrays the first one is the main array. The second is the array for my new data.
Let's say I have these arrays.
This is the main array:
Array
(
0 => Array
(
'id' => 1,
'name' => 'Apple',
'age' => 12
)
1 => Array
(
'id' => 2,
'name' => May,
'age' => 13
)
)
This is the second array:
Array
(
1 => Array
(
'gender' => 'Male'
)
2 => Array
(
'gender' => 'Female'
)
)
And I have this loop in PHP
foreach($main_array as &$main){
//this is the loop inside the first array
// how can I add the second array with it?
}
This is the sample output:
[0] => Array
(
[id] => 1
[name] => Apple
[age] => 12
[gender] => Female
)
[1] => Array
(
[id] => 2
[name] => May
[age] => 13
[gender] => Female
)
How can I do that? Any suggestions? That's all thanks.
for($i=0; $i<count($main_array); $i++){
for($j=0; $j<count($second_array); $j++){
if($main_array[$i]['id'] == $j){
$main_array[$i]['gender'] = $second_array[$j]['gender']
}
}
}
I fixed your example code, it wont run otherwise.
<?php
// Test data:
$main_array = Array(
0 => Array(
'id' => 1,
'name' => 'Apple',
'age' => 12
),
1 => Array (
'id' => 2,
'name' => 'May',
'age' => 13
)
);
$lookup = Array(
1 => Array(
'gender' => 'Male'
),
2 => Array(
'gender' => 'Female'
)
);
// Your answer:
foreach ($main_array as &$main) {
if (array_key_exists($main['id'],$lookup)) {
$main['gender'] = $lookup[$main['id']]['gender']; // <-- sets gender value
}
}
// Output it to browser:
echo '<pre>$main_array = '.print_r($main_array,true).'</pre>';
The array_key_exists() check is there to avoid errors such as PHP Notice: Undefined offset: 123 when the $lookup data is incomplete.
If you want to merge all of the data from both arrays:
PHP tools:
The exact behaviors of these functions needs to be studied and tested before usage, to make sure it fits your intent.
// array merge recursive doesn't merge numeric keys
$main_array = array_merge_recursive($main_array, $secondary_array);
// array replace recursive has a downside of replacing stuff
$main_array = array_replace_recursive($main_array, $secondary_array);
Rolling your own:
foreach($main_array as $i => &$main){
if(isset($secondary_array[$i])) {
foreach($secondary_array[$i] AS $key => $value) {
$main[$key] = $value;
}
}
}
Both of the above solutions only apply if the array-indexes of $main_array and $secondary_array match.
In your example your arrays don't match:
- $secondary_array[0] doesn't exist so $main_array[0] will not be populated with a 'gender' value;
- $main_array[2] doesn't exist so $main_array[2] will be created and it will only have a 'gender' value same as $secondary_array[2]['gender']
If you want to only merge some bits and pieces of the arrays:
Rolling your own:
foreach($main_array as $i => &$main) {
if(isset($secondary_array[$i])) and isset($secondary_array[$i]['gender'])) {
$main['gender'] = $secondary_array[$i]['gender'];
}
}
foreach($main_array as &$main){//this is the loop inside the first array
foreach($second_array as &$second){ //this is the loop inside the second array
}
}
foreach($arr1 as $k => $arr1Item) {
$arr1[$k]['gender'] = $arr2[$k]['gender'];
}

how to slip this multi-dimensional array?

I have a nested array and I wanted to know if there is a way to slip it, so having the nested arrays as individual arrays
Array
(
[0] => Array
(
[menu] => Array
(
[pizza] => Array
(
[Tomato & Cheese] => Array
(
[small] => 5.50
[large] => 9.75
)
[Olives] => Array
(
[small] => 6.85
[large] => 10.85
)
)
[Speciality Pizzas] => Array
(
[Our Special] => Array
(
[ingredients] => Array
(
[0] => Tomatoes
[1] => Olives
[2] => Spinach
[3] => Fresh Garlic
[4] => Mozzarella & Feta Cheese
) --- theres more but you get the idea
Now I want to may a new array with all the pizzas, but without knowing the name "pizza"
at the moment I can do this:
$array = array(json_decode($json, true));
$pizzas = (array)$array[0]['menu']['pizza']
But if the menu changes content (but not structure) and if the 'pizza' changes to 'salads' the above would fail. Is the a way to create the above pizzas array without the name
Thanks
$array = array(json_decode($json, true));
$menu = (array)$array[0]['menu'];
foreach($menu as $item => $item_Data){
//$item might be pizza for example
//$item_Data might be Olives or Our special. Now you have to consider what to do with this. Maybe next foreach loop ?
}
Right now your array has parallel sections for related data. How about if you did something like:
$food_choices = array(
'pizza' => array(
'Tomato & Cheese' => array(
'type' => 'regular',
'prices' => array(...),
'ingredients' => array(...)
),
'Our Special' => array(
'type' => 'specialty',
'prices' => array(...),
'ingredients' => array(...)
),
),
'salads' => array(
'Caesar' => array(...);
'Tossed' => array(...);
)
)
where all the information related to any one menu item as all in the same branch of the meu tree. Then to access any one pizza's information is as simple as:
$data = $food_choices['pizza']['Tomato & Cheese'];
echo 'The large of this pizza costs $', $data['prices']['large'];
echo 'The small Caesar salad contains ', implode($food_choices['salad']['Caesar']['ingredients);
A series of foreach loops might do, even though I don't know what you're doing.
<?php
$pizza = '';
foreach ($array as $food) {
$pizza .= $food;
if (is_array($food)) {
foreach ($food as $option) {
$pizza .= " > " . $option;
if (is_array($option)) {
foreach ($option as $value) {
//etc
}
}
}
}
}
?>
To learn about the keys in an array, use the array_keys function (Demo):
$array = array(array('menu' => array(/* ... */))); # your array
print_r(array_keys($array[0])); # Array(menu)

(PHP) Converting an array of arrays from one format into another

I currently have an array, created from a database, an example of which looks like the following:
Array(
[0] => Array (
objectid => 2,
name => title,
value => apple
),
[1] => Array (
objectid => 2,
name => colour,
value => red
),
[2] => Array (
objectid => 3,
name => title,
value => pear
),
[3] => Array (
objectid => 3,
name => colour,
value => green
)
)
What I would like to do is group all the items in the array by their objectid, and convert the 'name' values into keys and 'value' values into values of an associative array....like below:
Array (
[0] => Array (
objectid => 2,
title => apple,
colour => red
),
[1] => Array (
objectid => 3,
title => pear,
colour => green
)
)
I've tried a few things but haven't really got anywhere.. Any ideas?
Thanks in advance
This should work with your current setup and should be able to handle as many key-value pairs as available:
<?php
$results = array(
array('objectid' => 2, 'name' => 'title', 'value' => 'apple'),
array('objectid' => 2, 'name' => 'color', 'value' => 'red'),
array('objectid' => 3, 'name' => 'title', 'value' => 'pear'),
array('objectid' => 3, 'name' => 'color', 'value' => 'green'));
$final = array();
foreach ($results as $result) {
$final[$result['objectid']]['objectid'] = $result['objectid'];
$final[$result['objectid']][$result['name']] = $result['value'];
}
print_r($final);
It would be easier to have the array keys correspond with your object id, that way you can iterate through your existing array, and add the key-value pairs for each object, like so:
$newArray = array();
foreach ($results as $result) {
if (!array_key_exists($result['objectid'], $newArray)) {
$newArray[$result['objectid'] = array();
}
foreach ($result as $key => $value) {
$newArray[$result['objectid'][$key] = $value;
}
}
Peter's method is perfectly valid, I just thought I would show a shorter version of the same thing (couldn't do in a comment)
foreach( $array as $obj ) {
if( !isset( $objects[$obj['objectid']] ) )
$objects[$obj['objectid']]['objectid'] = $obj['objectid'];
$objects[$obj['objectid']][$obj['name']] = $obj['value'];
}

Categories