Associate PHP index with another array - php

I have 3 explode statements:
$emails = explode(',', $row['email']);
$firstnames = explode(',', $row['first_name']);
$lastnames = explode(',', $row['last_name']);
each explode produces three (3) arrays:
//emails
Array
(
[0] => test123#example.com
[1] => lol123#example.com
[2] => haha#example.com
[3] => blahblah#example.com
)
//first name
Array
(
[0] => Bill
[1] => Jake
[2] => John
[3] => Bob
)
//last name
Array
(
[0] => Jones
[1] => Smith
[2] => Johnson
[3] => Bakers
)
I can get the one array easily like this: for example:
foreach ($emails as $email) {
echo $email;
}
That will echo out the emails. But I want to add $firstname and $lastname into it. for example, I want to echo:
test123#example.com Bill Jones
how can i do it?

foreach can assign a key and value if you use the appropriate syntax:
foreach ($emails as $key => $email) {
echo $email;
echo $firstnames[$key];
echo $lastnames[$key];
}
Next time, consult the manual: http://php.net/manual/en/control-structures.foreach.php as this is shown at the very top.
As Pyromonk pointed out, for is useful in situations where you have indexed arrays:
for ($i = 0, $n = count($emails); $i < $n; $i++) {
echo $emails[$i];
echo $firstnames[$i];
echo $lastnames[$i];
}

Related

Is this possible for combining of two arrays, in PHP?

I have two arrays signatories and designations. Designations array has delimiter "|" indicating that 1 signatory has 2 designations. I'd like to output if the element has 2 value in delimiter and 1 in other array . It will produce another copy or clone. Like this.
$signatories = array('Allan','Robert','Maria');
$designations = array('CEO','CEO|COO','MANAGER|OIC|COO');
My expected output:
Allan - CEO
Robert - CEO
Robert - COO
Maria - MANAGER
Maria - OIC
Maria- COO
You need two loops and can use the same index.
$signatories = array('Allan|Joshua|Ronald', 'Robert|Mellisa', 'Maria');
$designations = array('CEO','CEO|COO','MANAGER|OIC|COO');
$cs = count($signatories);
for ($i=0; $i<$cs; $i++) {
$desigs = explode('|', $designations[$i]);
$signas = explode('|', $signatories[$i]);
foreach ($desigs as &$desig) {
foreach ($signas as &$signa) {
echo $signa.' - '.$desig.'<br>';
}
}
}
Using foreach loop and explode() function you can combine both array in a single array.
$signatories = array('Allan','Robert','Maria');
$designations = array('CEO','CEO|COO','MANAGER|OIC|COO');
$combinedArray = array();
foreach($signatories as $key => $value){
$combinedArray[] = array('name' => $value, 'designations' => explode("|",$designations[$key]));
}
print_r($combinedArray);die;
$combinedArray array has both name and array of designations.
Output of this array -
Array
(
[0] => Array
(
[name] => Allan
[designations] => Array
(
[0] => CEO
)
)
[1] => Array
(
[name] => Robert
[designations] => Array
(
[0] => CEO
[1] => COO
)
)
[2] => Array
(
[name] => Maria
[designations] => Array
(
[0] => MANAGER
[1] => OIC
[2] => COO
)
)
)
Bit messy but , with one loop.
<?php
$signatories = array('Allan','Robert','Maria');
$designations = array('CEO','CEO|COO','MANAGER|OIC|COO');
$i = 0;
foreach($designations as $designation) {
$newArr = explode('|',$designation);
echo $signatories[$i].' - '.implode('<br>'.$signatories[$i].' - ',$newArr).'<br><br>';
$i++;
}
One Another way,
$signatories = array('Allan','Robert','Maria');
$designations = array('CEO','CEO|COO','MANAGER|OIC|COO');
foreach($signatories as $key=>$val)
{
$exp = explode('|',$designations[$key]);
foreach($exp as $dsg)
{
echo $val.' - '.$dsg;
echo "<br>";
}
echo "<br>";
}
and your Output will be,
Allan - CEO
Robert - CEO
Robert - COO
Maria - MANAGER
Maria - OIC
Maria - COO

How to compare different arrays?

I need to show the email address, first and last names of users who are not registered in my new database.
I selected three columns of my old database and three columns of my new database. I created two arrays and each receives the result of the query.
But when the comparing is displaying all users, the comparison is not made.
Check my code:
while($array = $resultado->fetch_array(MYSQLI_NUM)){
$portal_old[] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_NUM)){
$portal_new[] = $array2;
}
foreach ($portal_old as $portal) {
if(!in_array($portal, $portal_new)){
$result[] = $portal;
}
}
Assuming email address should be able to uniquely identify a registered user, you can use email address as a key as you build your array of results from each database.
while($array = $resultado->fetch_array(MYSQLI_ASSOC)){
$portal_old[$array['email']] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_ASSOC)){
$portal_new[$array2['email']] = $array2;
}
In order for this to work, you will need to either use MYSQLI_ASSOC instead of MYSQLI_NUM when fetching, and specify the name of the email column when building your array, or if you are using MYSQLI_NUM, specify the numeric index of the email column.
Then you can use array_diff_key to easily find the result you are looking for.
$result = array_diff_key($portal_old, $portal_new);
This works, John Smith here gets in $result while Joe Black doesn't:
<?php
$name = array(0 => 'john', 1 => 'smith');
$portal_old[] = $name;
$name = array(0 => 'joe', 1 => 'black');
$portal_old[] = $name;
//print_r($portal_old);
//shows: Array ( [0] => Array ( [0] => john [1] => smith ) [1] => Array ( [0] => joe [1] => black ) )
$name = array(0 => 'jason', 1 => 'mill');
$portal_new[] = $name;
$name = array(0 => 'joe', 1 => 'black');
$portal_new[] = $name;
//print_r($portal_new);
//shows: Array ( [0] => Array ( [0] => jason [1] => mill ) [1] => Array ( [0] => joe [1] => black ) )
foreach($portal_old as $key=>$value) {
if(!in_array($value[0], $portal_new[0]) && !in_array($value[1], $portal_new[1])) {
$result[] = $value;
}
}
print_r($result);
//shows: Array ( [0] => Array ( [0] => john [1] => smith ) )
?>
It's because the results of $portal_old and $portal_new are multidimensional arrays, you need to compare by looking inside the arrays of the arrays.
This will work for you :
$i = $j = 0;
while($array = $resultado->fetch_array(MYSQLI_NUM)){
$portal_old[$i][$array['0'].' | '.$array['1'].' | '.$array['2']] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_NUM)){
$portal_new[$j][$array2['0'].' | '.$array2['1'].' | '.$array2['2']] = $array2;
}
// Get only array keys
$old_arr_key = array_keys($portal_old[0]);
$new_arr_key = array_keys($portal_new[0]);
// Result
$result = array_diff($new_arr_key,$old_arr_key);
print_r($result);

Associative index array to associative associative array

Problem
I have an array which is returned from PHPExcel via the following
<?php
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$excelFile = "excel/1240.xlsx";
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($excelFile);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$arrayData[$worksheet->getTitle()] = $worksheet->toArray();
}
print_r($arrayData);
?>
This returns:
Array
(
[Films] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => Shawshank Redemption
[1] => 39
)
[2] => Array
(
[0] => A Clockwork Orange
[1] => 39
)
)
[Games] => Array
(
[0] => Array
(
[0] => Name
[1] => Rating
)
[1] => Array
(
[0] => F.E.A.R
[1] => 4
)
[2] => Array
(
[0] => World of Warcraft
[1] => 6
)
)
)
What I would like to have is
Array
(
[Films] => Array
(
[0] => Array
(
[Name] => Shawshank Redemption
[Rating] => 39
)
[1] => Array
(
[Name] => A Clockwork Orange
[Rating] => 39
)
)
[Games] => Array
(
[0] => Array
(
[Name] => F.E.A.R
[Rating] => 4
)
[1] => Array
(
[Name] => World of Warcraft
[Rating] => 6
)
)
)
The arrays names (Films, Games) are taken from the sheet name so the amount can be variable. The first sub-array will always contain the key names e.g. Films[0] and Games[0] and the amount of these can be varible. I (think I) know I will need to do something like below but I'm at a loss.
foreach ($arrayData as $value) {
foreach ($value as $rowKey => $rowValue) {
for ($i=0; $i <count($value) ; $i++) {
# code to add NAME[n] as keys
}
}
}
I have searched extensively here and else where if it is a duplicate I will remove it.
Thanks for any input
Try
$result= array();
foreach($arr as $key=>$value){
$keys = array_slice($value,0,1);
$values = array_slice($value,1);
foreach($values as $val){
$result[$key][] = array_combine($keys[0],$val);
}
}
See demo here
You may use nested array_map calls. Somehow like this:
$result = array_map(
function ($subarr) {
$names = array_shift($subarr);
return array_map(
function ($el) use ($names) {
return array_combine($names, $el);
},
$subarr
);
},
$array
);
Demo
Something like this should work:
$newArray = array();
foreach ($arrayData as $section => $list) {
$newArray[$section] = array();
$count = count($list);
for ($x = 1; $x < $count; $x++) {
$newArray[$section][] = array_combine($list[0], $list[$x]);
}
}
unset($arrayData, $section, $x);
Demo: http://ideone.com/ZmnFMM
Probably a little late answer, but it looks more like your tried solution
//Films,Games // Row Data
foreach ($arrayData as $type => $value)
{
$key1 = $value[0][0]; // Get the Name Key
$key2 = $value[0][1]; // Get the Rating Key
$count = count($value) - 1;
for ($i = 0; $i < $count; $i++)
{
/* Get the values from the i+1 row and put it in the ith row, with a set key */
$arrayData[$type][$i] = array(
$key1 => $value[$i + 1][0],
$key2 => $value[$i + 1][1],
);
}
unset($arrayData[$type][$count]); // Unset the last row since this will be repeated data
}
I think this will do:
foreach($arrayData as $key => $array){
for($i=0; $i<count($array[0]); $i++){
$indexes[$i]=$array[0][$i];
}
for($i=1; $i<count($array); $i++){
for($j=0; $j<count($array[$i]); $j++){
$temp_array[$indexes[$j]]=$array[$i][$j];
}
$new_array[$key][]=$temp_array;
}
}
print_r($new_array);
EDIT: tested and updated the code, works...

Getting multi dimensional array to create new arrays based on index value

I am having a terrible time getting this to work I have been struggling with it for a couple hours now. Can someone please help me? I have included a fiddle.
I believe my problem is in this string:
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
Basically I have the following multidimensional array:
[sales] => Array
(
[FirstName] => Array
(
[0] => salesFirst1
[1] => salesFirst2
)
[LastName] => Array
(
[0] => salesLast1
[1] => salesLast2
)
)
[decisionmaker] => Array
(
[FirstName] => Array
(
[0] => dmFirst1
[1] => dmFirst2
)
[LastName] => Array
(
[0] => dmLast1
[1] => dmLast2
)
)
)
I need this to be reorganized like I did with the following array:
Array
(
[additionallocations0] => Array
(
[Address] => Address1
[State] => State1
)
[additionallocations1] => Array
(
[Address] => Address2
[State] => State2
)
)
Here is the original:
Array
(
[additionallocations] => Array
(
[Address] => Array
(
[0] => Address1
[1] => Address2
)
[State] => Array
(
[0] => State1
[1] => State2
)
)
This is how I reorganize the above array:
if(isset($_POST['additionallocations'])) {
$qty = count($_POST['additionallocations']["Address"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST['additionallocations'] as $param => $values)
{
$additional['additionallocations'.$l][$param] = $values[$l];
}
}
And this is what I am using for the sales and decisionmaker array. If you notice I have an array that contains sales and decisionmaker in it. I would like to be able to sort any future arrays by just adding its primary arrays name. I feel I am close to solving my problem but I can not get it to produce right.
$salesAndOwner = array(0 => "sales", 1 => "decisionmaker");
for($i = 0; $i < 2; $i++){
$qty = count($_POST[$salesAndOwner[$i]]["FirstName"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST[$salesAndOwner[$i]] as $param => $values)
{
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
}
}
}
In the above code I hard coded 'sales' into the variable I need it to make a variable name dynamically that contains the sales0 decisionmaker0 and sales1 decisionmaker1 arrays so $sales and $decisionmaker
I hope this makes sense please let me know if you need any more info
Let's break it down. Using friendly variable names and spacing will make your code a lot easier to read.
Remember. The syntax is for you to read and understand easily. (Not even just you, but maybe future developers after you!)
So you have an array of groups. Each group contains an array of attributes. Each attribute row contains a number of attribute values.
PHP's foreach is a fantastic way to iterate through this, because you will need to iterate through (and use) the index names of the arrays:
<?php
$new_array = array();
// For each group:
foreach($original_array as $group_name => $group) {
// $group_name = e.g 'sales'
// For each attribute in this group:
foreach($group as $attribute_name => $attributes) {
// $attribute_name = e.g. 'FirstName'
// For each attribute value in this attribute set.
foreach($attributes as $row_number => $attribute) {
// E.g. sales0
$row_key = $group_name . $row_number;
// if this is the first iteration, we need to declare the array.
if(!isset($new_array[$row_key])) {
$new_array[$row_key] = array();
}
// e.g. Array[sales0][FirstName]
$new_array[$row_key][$attribute_name] = $attribute;
}
}
}
?>
With this said, this sort of conversion may cause unexpected results without sufficient validation.
Make sure the input array is valid (e.g. each attribute group has the same number of rows per group) and you should be okay.
$salesAndOwner = array("sales", "decisionmaker");
$result = array();
foreach ($salesAndOwner as $key) {
$group = $_POST[$key];
$subkeys = array_keys($group);
$first_key = $subkeys[0];
foreach ($group[$first_key] as $i => $val) {
$prefix = $key . $i;
foreach ($subkeys as $subkey) {
if (!isset($result[$prefix])) {
$result[$prefix] = array();
}
$result[$prefix][$subkey] = $val;
}
}
}
DEMO
Try
$result =array();
foreach($arr as $key=>$val){
foreach($val as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$result[$key.$key2][$key1] = $val2;
}
}
}
See demo here

String exploded twice array foreach loop

I have this code:
$sample = '5ml milk, 5ml water, 3pcs carrots';
echo $sample."</br>";
$first_slice = explode(',',$sample);
foreach($first_slice as $key => $value)
{
$second_slice[$key] = explode(' ',$value);
}
print_r($second_slice);
It does what i want, i need to separate 5ml milk from 5ml water and 3pcs carrots
from there i need to separate again 5ml from milk.
My question is, how do i select/echo only 5ml and milk as a single data.
The above code produces the result:
Array ( [0] => Array ( [0] => 5ml [1] => milk ) [1] => Array ( [0] =>
[1] => 5ml [2] => water ) [2] => Array ( [0] => [1] => 3pcs [2] =>
carrots ) )
Im quite confused on how do i select/echo since i exploded it twice means its an array inside an array. Please correct me if my understanding is wrong.
Additional question: I have to explode it thrice. Since my table has name,quantity,unit columns.
name for the ingredient name, quantity for the quantity, unit for the unit of measurement.
respectively [milk] [5] [ml]
I have done the same to make another array for separating measurement and quantity. But it cancels out the redundancy.
foreach($second_slice as $key=>$value)
{
$arr = explode('-',$value);
$third_slice[$arr[1]] = $arr[0];
}
The output is:
Array ( [ml] => 5 [pcs] => 3 )
There are 2 5ml's on the string. How do i not avoid it being taken out? since they are separate ingredients.
Currently, you have a multi-dimensional array. You can simpify this approach and flatten your array to one dimension. I suggest you modify your foreach loop as below:
foreach($first_slice as $key => $value)
{
$arr = explode(' ', trim($value));
$second_slice[$arr[1]] = $arr[0];
}
print_r($second_slice);
Produces the output:
Array
(
[milk] => 5ml
[water] => 5ml
[carrots] => 3pcs
)
Now, to get the quantity for any item, you can directly do echo $second_slice['item_name'].
And if you wanted to find the name of the quantity from the amount, you can use array_search():
$searchFor = '3pcs';
echo array_search($searchFor, $second_slice);
Outputs:
carrots
If there are multiple quantities with the same amount, the above method only returns the first. If you want to get all of them, you can use array_filter():
$result = array_filter($second_slice, function($elem) use ($searchFor){
return ($elem == $searchFor);
});
print_r($result);
Output:
Array
(
[milk] => 5ml
[water] => 5ml
)
You just want to output 5ml milk? Because if so, simply do the following:
echo $first_slice[0];
There is a hidden whitespace problem, but you can easily fix it with the following code by using trim:
$sample = '5ml milk, 5ml water, 3pcs carrots';
echo $sample."</br>";
$first_slice = explode(',',$sample);
foreach($first_slice as $key => $value)
{
$second_slice[$key] = explode(' ',trim($value));
}
print_r($second_slice);
which produces the following array:
Array
(
[0] => Array
(
[0] => 5ml
[1] => milk
)
[1] => Array
(
[0] => 5ml
[1] => water
)
[2] => Array
(
[0] => 3pcs
[1] => carrots
)
)
there are a few ways you can achieve this. Here is one way:
$sample = '5ml milk, 5ml water, 3pcs carrots';
$items = explode(",", $sample);
$final = array();
foreach($items as $i){
$value = explode(" ", trim($i));
$final[$value[1]] = $value[0];
}
echo "<pre>";
print_r($final);
echo "</pre>";
If you want to echo "5ml milk":
echo $second_slice[0][0] . " " . $second_slice[0][1];
echo "5ml water";
echo $second_slice[1][0] . " " . $second_slice[1][1];
echo "3pcs carrots";
echo $second_slice[2][0] . " " . $second_slice[2][1];

Categories