So currently I have an array that pulls data based on an attribute and it puts the data in its own seperate array. What I need to do is to put these 3 arrays into one, so if one of them is null, it won't give me errors. It should be fairly simply but I can't wrap my head around it.
//CV eqpValue
if (is_array(FullDataResponse->dlr->DesignLayoutRecord)) {
foreach(FullDataResponse->dlr->DesignLayoutRecord as $DesignLayoutRecord_key => $DesignLayoutRecord_value ) {
if ($DesignLayoutRecord_value->cktEqpOptions->CktEqpOptions && is_array($DesignLayoutRecord_value->cktEqpOptions->CktEqpOptions)) {
foreach ($DesignLayoutRecord_value->cktEqpOptions->CktEqpOptions as $cv_obj)
{
if($cv_obj->attribute === 'CDR')
{
$this->cvCDRList[] = array("cdr" => $cv_obj->eqpValue);
}
if($cv_obj->attribute === 'CUSTOMER')
{
$this->cvCustomerList[] = array("customer" => $cv_obj->eqpValue);
}
if($cv_obj->attribute === 'LEASE LINE')
{
$this->cvphoneList[] = array("phoneNumber" => $cv_obj->eqpValue);
}
}
}
}
}
See how they are currently put into separate arrays like cvCDRList, cvCustomerList, and cvphoneList? How would I put them into a single array? Thanks!!
you can use array_merge.
<?php
$array1 = array("a12","a12","a13");
$array2 = array("a21","a22","a23");
$array3 = array("a31","a32","a33");
$finalArray = array_merge($array1,$array2,$array3);
foreach( $finalArray as $key => $value ){
echo $key."=>".$value."<br>";
}
?>
You can create another property called "allAtributes" .
When you finalize to fill your 3 arrays you can call to another method of class than make the merge between 3 array.
The finally you will have got like this :
allAtributes (array)=>{
["cdr"](array)=> {
['cdrkey1'] = cdrAtt1 ,
['cdrKey2'] = cdrAtt2 ...
},
["customer"](array)=> {
['customerkey1'] = customerAtt1 ,
['customerKey2'] = customerAtt2 ...
},
["phoneNumber"](array)=> {
['phoneNumberkey1'] = phoneNumberAtt1 ,
['phoneNumberKey2'] = phoneNumberAtt2 ...
}
}
You only must declare an array an add the other three arrays with the function array_merge into loops
Related
This question already has answers here:
PHP array replace after matching value [duplicate]
(2 answers)
Closed 2 months ago.
Am using Php as my serverside scripting language.In my project I used Json string decoded into array.
My problem is how to overwrite the existing array index based on an array value.
my existing array looks like :
$array1 =[
{
"Name":"apple",
"color":"red",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
and the updated array content looks:
$upadatearray = [
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
}
];
I want to update the existing $array1 with new $upadatearray , bsed on the "Name" .If it is same then replace.
I want to look like:
$finalarray =[
{
"Name":"apple",
"color":"green",
"property":[
{
"p1":"newvalue",
"p2":"newvalue2"
}
]
},
{
"Name":"Grape",
"color":"violet",
"property":
[
{
"p1":"value1",
"p2":"value2"
}
]
}
];
I tried this :
for($j=0;$j<count($array1);$j++)
{
if($array1[$j]['Name'] == $upadatearray[0]['Name'])
$finalarray = array_replace($array1[$j],$upadatearray[0]);
}
But it will not work correctly.Is there any possible solution ?
Let you have this two arrays:
$array1 ='[{"Name":"apple","color":"red","property":[{"p1":"value1","p2":"value2"}]},{"Name":"Grape","color":"violet","property":[{"p1":"value1","p2":"value2"}]}]';
$upadatearray = '[{"Name":"apple", "color":"green", "property":[{"p1":"newvalue","p2":"newvalue2"}]}]';
$array1 = json_decode($array1, true);
$upadatearray = json_decode($upadatearray, true);
You can use array_replace function. But to make it replace items based on the Name column you should first make this column a key of array
function make_column_key($arr, $col_name) {
$keys = array_column($arr, $col_name);
$result = array_combine($keys, $arr);
return $result;
}
$array1 = make_column_key($array1, 'Name');
$upadatearray = make_column_key($upadatearray, 'Name');
And now simply use array_replace
$finalarray = array_replace($array1, $upadatearray);
If you don't need Name be the key of final array, you can get only values:
$finalarray = array_values($finalarray);
hi I think this code will help you.
//what i did is i created a final array variable which gets the value of old array.
$finalArray = $array1;
//then i perform a foreach loop for old array
foreach ($array1 as $key => $oldarray) {
//inside the updated array
foreach ($upadatearray as $key => $newarray) {
//if old array name and new array name is same replace content on the final array
if ($oldarray['Name'] == $newarray['Name']) {
$finalArray['Name'] = $newarray['Name'];
}
}
}
I had a problem with this particular code. The conditions are:
When $rows['Machine#'] is not in array, push in $machineArr array and unset the $totalTimeArr array.
When $rows['Machine#'] is in the array, push $rows['TotalTime'] into $totalTimeArr array for addition.
$graphArr[] should be updated (for array_sum($totalTimeArr)) first before push into array.
only one $graphArr[] for each machine
I now have problems regarding the third condition. It does not calculate first, instead it pushes the first data input. I have tried using do while loop, putting $graphArr[] = '["'.$rows['Machine#'].'",'.array_sum($totalTimeArr).']'; outside the if else loop, but this seems to be the closest I can get to what it's supposed to be. Other codes don't seem to have any problems and work well. Appreciate your recommendations/suggestions/assistance. Below is the code.
while ($rows = mysqli_fetch_array($conn))
{
if(!(in_array($rows['Machine#'], $machineArr)))
{
unset($totalTimeArr);
$machineArr[] = $rows['Machine#'];
$totalTimeArr[] = $rows['TotalTime'];
$graphArr[] = '["'.$rows['Machine#'].'",'.array_sum($totalTimeArr).']';
}
else if(in_array($rows['Machine#'], $machineArr))
{
$totalTimeArr[] = $rows['TotalTime'];
}
}
EDIT: I'm currently on this:
while ($rows = mysqli_fetch_array($conn))
{
$exists = false;
if( in_array($rows['Machine#'], $machineArr) )
{
$exists = true;
}
$totalTimeArr[] = $rows['TotalTime'];
if($exists === false)
{
$totalTimeArr = array();
$machineArr[] = $rows['Machine#'];
$totalTimeArr[] = $rows['TotalTime'];
}
$graphArr[] = '["'.current($machineArr).'",'.array_sum($totalTimeArr).']';
next($machineArr);
}
The result:
Array ( [0] => ["09CS1", 1.4]
[1] => ["08CS1", 1 ]
[2] => ["06CS1", 1 ]
[3] => ["" , 1.5]
[4] => ["02CS2", 1 ]
[5] => ["01CS2", 20 ]
[6] => ["" , 40 ]
[7] => ["01CS1", 1 ]
)
How do I remove ["", 1.5] and ["", 40]?
Below is the database:
I'm not sure what you need to do, if you need a running sum for a specific type of a machine then do something like:
$totalTileArr = [];
while ($rows = mysqli_fetch_array($conn)) {
if (!isset($totalTileArr[$rows['Machine#']])) {
$totalTileArr[$rows['Machine#']] = [];
}
$totalTimeArr[$rows['Machine#']][] = $rows['TotalTime'];
$graphArr[$rows['Machine#']] = '["' . $rows['Machine#'] . '",' . array_sum($totalTimeArr[$rows['Machine#']]) . ']';
}
A slightly modified version of your code cleaned up
$machineArr = Array();
while ($rows = mysqli_fetch_array($conn)) {
$exists = false;
if( in_array($rows['Machine#'], $machineArr) ) { $exists = true; }
$totalTimeArr[] = $rows['TotalTime'];
if($exists === false) {
unset($totalTimeArr);
$machineArr[] = $rows['Machine#'];
$totalTimeArr[] = $rows['TotalTime'];
$graphArr[] = '["'.$rows['Machine#'].'",'.array_sum($totalTimeArr).']';
}
}
Converted the check into one in_array() search, then comparing using === bitwise operator to evaluate the condition. Also defined $machineArr as an Array() as the first check in your loop would always fail given that $machineArr was (presumably as I don't see the code prior to the while loop) undefined.
I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}
I have an array with structure generated like this:
$groups = array();
while ($group = mysql_fetch_array($groups_result)) {
$groups[] = array( 'id' => $group['id'], 'name' => $group['name']);
}
How can I later in the code get the name of the group by its id? For example, I would like a function like:
function get_name_by_id($id, $array);
But I'm looking for some solution which is already implemented in PHP. I know it would be easier to make arrays with array[5] = array('name' => "foo") etc where 5 in this case is id, but in my code there is a lot of arrays already created like i mentioned above and I cannot easily switch it.
$groups = array();
while ($group = mysql_fetch_assoc($groups_result)) {
$groups[$group['id']] = array( 'name' => $group['name']);
}
$name = $groups['beer']['name'];
also please not using fetch_assoc is more efficient than fetch array
function get_name_by_id($id, $data) {
foreach($data as $d) {
if ($d['id'] == $id) {
return $d['name'];
}
}
// return something else, id was not found
}
I have an nested array that's a mix of words and numbers. It looks like this conceptually. I need to process only numbered indexes such as 15 and 28. I guess this means that I can't use a foreach loop (or is there a way I could). How would you do this?
myarray = (
someindex = (
field1 =
field2 =
);
15 = (
field1 =
field2 =
);
28 = (
field1 =
field2 =
);
anothertext = (
field1 =
field2 =
);
);
foreach($myarr as $key => $item)
{
if(is_int($key))
{
// Do processing here
}
}
Yes, that will loop through every item in the array, so if you wanted to process the other items separately, you could just add in an else block.
Edit: Changed is_numeric to is_int. See comments for explanation.
You can use foreach
foreach($myarray as $key=>$value)
{
if(is_int($key))
{
//process the entry as you want
}
}
You could use a FilterIterator with foreach:
class IntKeyFilterIterator extends FilterIterator {
public function accept() {
return is_int(parent::key());
}
}
$it = new IntKeyFilterIterator(new ArrayIterator($array));
foreach ($it as $value) {
// Will only have those with int keys
}
Another version. Grep the source array for any purely numeric keys, then loop over that result array and do the processing.
$keys = preg_grep('/^\d+$/', array_keys($myarray)) {
foreach($keys as $key) {
doSomething($myarray[$key]);
}