I have a arrays like this.
$pahrmacyid=array(
"Identification"=>array(
"ID"=>array(
"IDValue"=>$_GET['pharmacyid'],
"IDQualifier"=>"D3"
)
)
);
$storename=array(
"StoreName"=>$_GET['storename']
);
$pharmacyaddress=array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
);
$communicationnumber=array(
"CommunicationNumbers"=>array(
"Communication"=>array(
"Number"=>$_GET['pCommunicationNumbers'],
"Qualifier"=>"TE"
)
)
);
I want to push this arrays into another array?Is it possible?
I need a result like this:
$result=array(
array("Identification"=>array(
"ID"=>array(
"IDValue"=>$_GET['pharmacyid'],"IDQualifier"=>"D3"
)
)
),
"StoreName"=>$_GET['storename'],array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
),
array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
)
)
It's simple since you have all the array's. Here are a couple of ways to merging all the array's into one multidimensional array.
Example 1:
$example1arr = array(
$pahrmacyid,
$storename,
$pharmacyaddress,
$communicationnumber
);
echo "Example 1: <pre>".print_r($example1arr,true)."</pre><br />\n";
Example 2:
$example2arr[] = $pahrmacyid;
$example2arr[] = $storename;
$example2arr[] = $pharmacyaddress;
$example2arr[] = $communicationnumber;
echo "Example 2: <pre>".print_r($example2arr,true)."</pre><br />\n";
Example 3:
$example3arr = Array();
array_push(
$example3arr,
$pahrmacyid,
$storename,
$pharmacyaddress,
$communicationnumber
);
echo "Example 3: <pre>".print_r($example3arr,true)."</pre><br />\n";
$result[] = $pahrmacyid;
And if you have multiple $pahrmacyid-arrays you can add it in a loop.
$result = array();
for($i = 0; $i < count($sourceArray); $i++)
{
$result[] = $sourceArray[$i];
}
$result[] = $pahrmacyid;
You may want to initilize it before with
$result = array();
And I didn't try but maybe the shortcut
$result = array($pahrmacyid);
works...
array_push($result, $pahrmacyid)
or
$result[] = $pahrmacyid
any of these two should do the trick
Related
I'm having a hard time figuring out how to implement this so here it is. I have an array
$arr = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1",
2=>"POD2",
),
"quantity_received"=>array(
0=>5,
1=>10,
2=>20
)
);
I want to split the arrays into two. Into something like this.
$pod_2 = array("purchase_order_details_id"=>array(
0=>"POD1",
1=>"POD1"
),
"quantity_received"=>array(
0=>5,
1=>10
));
$pod_1 = array("purchase_order_details_id"=>array(
2=>"POD2"
),
"quantity_received"=>array(
2=>20
));
Anyone has an idea on how to do this ? Any thoughts is appreciated. Thanks
I use array_intersect to find the POs in a loop of unique POs.
Then I use array_inyersect_key to get the quantity.
This requires only one iteration per unique Purchase_order_detali_id.
Meaning it has a much better performance than looping the full array.
Edit: added extract to create the two variables. But I would rather keep them in the array if I was you.
$pods = array_unique($arr["purchase_order_details_id"]);
Foreach($pods as $pod){
$PO = array_intersect($arr["purchase_order_details_id"], [$pod]);
$qt = array_intersect_key($arr["quantity_received"], $PO);
$new[$pod] = ["purchase_order_details_id" => $PO, "quantity_received" => $qt];
}
Var_dump($new);
extract($new);
https://3v4l.org/dBpuJ
Try with below code:
$array = array();
foreach($arr['purchase_order_details_id'] as $key => $val)
{
$array[$val]['purchase_order_details_id'][] = $val;
$array[$val]['quantity_received'][] = $arr['quantity_received'][$key];
}
echo "<pre>";
print_r($array);
echo "</pre>";
extract($array);
echo "<pre>";
print_r($POD1);
echo "</pre>";
echo "<pre>";
print_r($POD2);
echo "</pre>";
foreach ($arr as $key => $val) {
$size = ceil(count($val) / 2);
$arr2 = array_chunk($val, $size, true);
$pod_2[$key] = $arr2[0];
$pod_1[$key] = $arr2[1];
}
var_dump($pod_2);
var_dump($pod_1);
I have an array
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
I want to convert this to
$multiarr=array(
[0]=>array(
['id']=>1,
['name']=>'abc'),
[1]=>array(
['id']=>2,
['name']=>'xyz'),
[2]=>array(
['id']=>3,
['name']=>'pqr')
);
id is key and the name is the value of the first array
how can I implement this optimistically
I have done this
$keys=array_keys($arr);
$values=array_values($arr) ;
$multiarr=array();
for($i=0; $i<count($keys); $i++)
{
$multiarr[$i]['id']=$keys[$i];
$multiarr[$i]['name']=$values[$i];
}
Thanks.
Should really be trying this yourself mate, but this should help:
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
$MultiArr = array();
$i = 0;
foreach($arr as $ID=>$Name){
$MultiArr[$i]['id'] = $ID;
$MultiArr[$i]['name'] = $Name;
$i++;
}
print_r($MultiArr);
I have this PHP foreach loop:
foreach($emails_list as $email)
but i want to do something like
foreach($emails_list as $email and $forename_list as $forename)
my code above the foreach loop is:
$sql2="SELECT * from contacts where company_sequence = '".$customersequence."' and contactstatus = '' ";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
while($result2=mysql_fetch_array($rs2))
{
$emails_list[] = $result2["email"];
}
si i want to be able to include $result["forename"]; within the loop too
will the above work to make 2 loops?
Not sure if understand, but try use for instead:
$emails_list = array("01#gmail.com", "02#gmail.com", "03#gmail.com", "04#gmail.com");
$forename_list = ("01 something", "02 something", "03 something", "04 something");
if($emails_list == $forename_list){
$count = count($emails_list);
for($i=0;$i<$count;$i++){
echo 'Email: '.$emails_list[$i].', Name: '.$forename_list[$i];
}
} else { echo 'Troubles'; }
there is no way to do this in foreach in a one statment
for this use for loop like
for ($i=0;$i<=count($emails_list); $i++) {
echo $emails_list[$i];
echo $forename_list[$i];
}
All the examples listed with a basic for loop will work fine for numeric arrays, however what about associative arrays?
The best way to do this would be something like the following:
$arr_1 = array( 'foo'=>'bar', 'fizz'=>'bang' );
$arr_2 = array( 'hello'=>1, 2=>'world' );
$array_size = count( $arr_1 ); // NOTE: This assumes the arrays are of the same size.
// Reset the internal array pointers
reset( $arr_1 );
reset( $arr_2 );
for ($i = 0; $i < $array_size; $i++ ) {
$first_array_element = current( $arr_1 );
$second_array_element = current( $arr_2 );
// code here
next( $arr_1 );
next( $arr_2 );
}
This will handle both associative and numeric arrays.
Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";
I have a array of associative arrays
aa[] = ('Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 );
aa[] = ('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>3 );
aa[] = ('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>44 );
aa[] = ('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>45 );
aa[] = ('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>433 );
aa[] = ('Tires'=>23, 'Oil'=>33, 'Spark Plugs'=>44 );
Two Questions
How can I remove duplicates according tot he field 'Oil'
is there a array_unique which I can provide a callback which acts as a custom comparator?
How can I sort by a custom field 'Spark Plugs'
I don't know of a function you can use to do this. You will have to do a foreach over the values of the array and do the uniqueness checking manually.
Use the usort() function and provide a custom comparator.
Instead of manually going and doing the usual duplicate checking, I did this
$aa2 = array()
foeach($aa as $key => $value) {
$aa2[$value['Oil']] = $value;
}
$aa = $aa2;
Then sorting was done by the key...
For question 1, I think array_filter is what you need.
And, like Brian says, usort for your second question.
The issue with remove dupes this way, is how do you determine which values remain, since you're talking about partial uniqueness.
This solution below just keeps the first to appear in index-order. It's not exactly elegant, but it works.
<?php
$aa = array();
$aa[] = array('Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 );
$aa[] = array('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>3 );
$aa[] = array('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>44 );
$aa[] = array('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>45 );
$aa[] = array('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>433 );
$aa[] = array('Tires'=>23, 'Oil'=>33, 'Spark Plugs'=>44 );
echo '<pre>';
print_r( arrayUniqeBySubKey( $aa, 'Oil' ) );
echo '</pre>';
function arrayUniqeBySubKey( $array, $key )
{
$indexAggregates = array();
foreach ( $array as $idx => $subArray )
{
$indexAggregates[$subArray[$key]][] = $idx;
}
foreach ( $indexAggregates as $originalIndexes )
{
$numOriginals = count( $originalIndexes );
if ( 1 == $numOriginals )
{
continue;
}
for ( $i = 1; $i < $numOriginals; $i++ )
{
unset( $array[$originalIndexes[$i]] );
}
}
return $array;
}
You can indeed use array_filter for filtering your data:
$bb = array_filter($aa, function($item) {
static $tmp = array();
if ($filter = !in_array($item['Oil'], $tmp)) {
$tmp[] = $item['Oil'];
}
return $filter;
});
This uses a static variable inside the function to "remember" the Oil already returned. This works, because $tmp is used only during the execution of array_filter. If you wrap this into a function and call it multiple times for example, $tmp will always be an empty array for the first call of the function provided to array_filter.
The second task, the sorting, can be done using usort with a custom sorting function:
usort($bb, function($a, $b) {
return ($a['Spark Plugs'] > $b['Spark Plugs']
? 1
: -1);
});