Is this possible for combining of two arrays, in PHP? - 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

Related

PHP multiple array value on one assosiate array

This is my array
Array
(
[0] => Array
(
[0] => Music One
[1] => Two
)
[1] => Array
(
[0] => C:\fakepath\Shape of You - Ed Sheeran (DJJOhAL.Com).mp3
[1] => C:\fakepath\I m The One Ft Justin Bieber Quavo Chance The Rapper Lil Wayne - DJ Khaled (DJJOhAL.Com).mp3
[2] =>
)
)
And I want like this
Array
(
[0] => Array
(
[releasetrack_track_title] => Music One
[releasetrack_mp3_demo] => C:\fakepath\Shape of You - Ed Sheeran (DJJOhAL.Com).mp3sample-DJ026-2.mp3
)
[1] => Array
(
[releasetrack_track_title] => Two
[releasetrack_mp3_demo] => C:\fakepath\I m The One Ft Justin Bieber Quavo Chance The Rapper Lil Wayne - DJ Khaled (DJJOhAL.Com).mp
)
)
How is it possible i have also used function array_merge_recursive but i did not get output that i want.
Does anyone know about it then please share me code.
You need specific customization to manage your array, i had face same issue with customization, Please try below mention code, defiantly it will helpful,
<?php
$yourArr; //Your Requested array
$outputArr = [];
foreach ($yourArr as $i => $val)
{
foreach ($val as $j => $con)
{
if($j == 0) { $outputArr[$i]['releasetrack_track_title'] = $con; }
if($j == 1) { $outputArr[$i]['releasetrack_mp3_demo'] = $con; }
}
}
echo "<pre>"; print_r($outputArr); die();
?>
You can try like this, live demo
$result = [];
foreach(range(0, count($array[0]) - 1) as $i)
{
$result[] = array_combine(['releasetrack_track_title', 'releasetrack_mp3_demo'], array_column($array, $i));
}
You have no other way than just loop and to new array:
$newArray = [];
foreach ($oldArray as $index => $items) {
switch ($index) {
case 0:
$key = 'releasetrack_track_title';
break;
case 1:
$key = 'releasetrack_mp3_demo';
break;
}
foreach ($items as $subIndex => $value) {
$newArray[$subIndex][$key] = $value;
}
}
Use foreach function over array[0] i.e. title array. Below is the code:
$newarr=array();
$music = Array(
[0] => Array
(
[0] => Music One
[1] => Two
)
[1] => Array
(
[0] => C:\fakepath\Shape of You - Ed Sheeran (DJJOhAL.Com).mp3
[1] => C:\fakepath\I m The One Ft Justin Bieber Quavo Chance The Rapper Lil Wayne - DJ Khaled (DJJOhAL.Com).mp3
[2] =>
)
)
foreach($music[0] as $key=>$value){
$newarr[$key]['releasetrack_track_title']=$value;
$newarr[$key]['releasetrack_mp3_demo']=$music[1][$key];
}
print_r($newarr);
<?php
$arr = array(array(" Music One","C:\fakepath\Shape of You - Ed Sheeran (DJJOhAL.Com).mp3sample-DJ026-2.mp3"),array("Two", "C:\fakepath\I m The One Ft Justin Bieber Quavo Chance The Rapper Lil Wayne - DJ Khaled (DJJOhAL.Com).mp"));
echo'<pre>';
print_r($arr);
?>

Associate PHP index with another array

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];
}

Is this possible for combining of two arrays in PHP? (part 2)

This is my part2 of my question, following part 1.
I have two arrays signatories and designations. Signatories and Designations arrays have delimiter "|" indicating that each have 1,2 or more signatories same as in designations, depends on how many delimiter. I'd like to output if the element has 1, 2 or more values in delimiter and in other array . It will produce another copy or clone. Like this:
$signatories = array('Allan|Joshua|Ronald' , 'Robert|Mellisa' , 'Maria');
$designations = array('CEO|OIC' , 'CEO|COO|MANAGER' , 'MANAGER|OIC|COO');
My Expected Output:
***Array [0]***
Allan - CEO
Joshua - CEO
Ronald- CEO
Allan - OIC
Joshua - OIC
Ronald- OIC
***Array [1]***
Robert - CEO
Mellisa - CEO
Robert - COO
Mellisa - COO
Robert - MANAGER
Mellisa - MANAGER
***Array [2]***
Maria - MANAGER
Maria - OIC
Maria- COO
A functional approach (easist to understand if read from behind/buttom-up):
$signatories = array('Allan|Joshua|Ronald', 'Robert|Mellisa', 'Maria');
$designations = array('CEO|OIC','CEO|COO','MANAGER|OIC|COO');
$result = array_map(function ($names, $titles) {
return call_user_func_array('array_merge', array_map(function ($name) use ($titles) {
return array_map(function ($title) use ($name) {
return $name . ' - ' . $title;
}, explode('|', $titles));
}, explode('|', $names)));
}, $signatories, $designations);
This produces a result like this:
Array
(
[0] => Array
(
[0] => Allan - CEO
[1] => Allan - OIC
[2] => Joshua - CEO
[3] => Joshua - OIC
[4] => Ronald - CEO
[5] => Ronald - OIC
)
[1] => Array
(
[0] => Robert - CEO
[1] => Robert - COO
[2] => Mellisa - CEO
[3] => Mellisa - COO
)
[2] => Array
(
[0] => Maria - MANAGER
[1] => Maria - OIC
[2] => Maria - COO
)
)
This solution uses built-in PHP functions to solve the problem:
First, the two arrays are "zipped" together with array_map.
Then for each name it is combined with each title in the pair.
Lastly, the array is flattened.
PHP doesn't have an array flatten function that is what this is for:
call_user_func_array('array_merge', $input);
You could also look into using RecursiveIterator from SPL
<?php
$signatories = array('Allan|Joshua|Ronald' , 'Robert|Mellisa' , 'Maria');
$designations = array('CEO|OIC' , 'CEO|COO|MANAGER' , 'MANAGER|OIC|COO');
if (count($signatories) > count($designations))
Die("Sorry, but number of signatories is larger than number of designations, cannot continue.");
$result = [];
foreach ($signatories as $k => $v) {
$subresult = [];
$e = explode('|', $v);
$e2 = explode('|', $designations[$k]);
foreach ($e as $name) {
foreach ($e2 as $designation) {
$subresult[] = $name.' - '.$designation;
}
}
$result[] = $subresult;
}
echo "<pre>";
var_dump($result);
echo "</pre>";
$signatories = array('Allan|Joshua|Ronald' , 'Robert|Mellisa' , 'Maria');
$designations = array('CEO|OIC' , 'CEO|COO|MANAGER' , 'MANAGER|OIC|COO');
foreach($signatories as $key=>$item){
$itemSet = explode('|', $item);
foreach($itemSet as $row){
$desSet = explode('|', $designations[$key]);
foreach($desSet as $pos){
echo $row." - ".$pos;
echo "<br/>";
}
}
}
You need two loops and can use the same index.
$signatories = array('Allan|Joshua|Ronald', 'Robert|Mellisa', 'Maria');
$designations = array('CEO|OIC', 'CEO|COO|MANAGER', '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>';
}
}
}

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];

SELECT some_value FROM php_array WHERE other_values (not mysql !)

In MySQL I can SELECT a value from one column of a row WHERE one or more columns have a specified value:
SELECT name FROM table WHERE birthyear = '1965' AND birthplace = 'Vancouver'
Now I have a multidimensional PHP_array (not a mySQL database), and I would like to extract the name from the row for a given birthyear and birthplace in a similar manner. This is the array:
$example = Array
(
[0] => Array
(
[0] => 1965
[1] => Bob
[2] => Vancouver
)
[1] => Array
(
[0] => 1973
[1] => John
[2] => Vancouver
)
[2] => Array
(
[0] => 1965
[1] => Paul
[2] => Houston
)
)
It seems to me that for each WHERE-condition I would need one loop in PHP. If you assume that I need to match several columns (birthday, birthplace, sex, occupation etc.), you'll understand how this slows down the execution over an array with thousands of entries.
How can I do this with the least number of loops?
array_filter($example,function($v) { return $v[0] == 1982; });
This function will do what you are looking for:
function getNameByYear($year, array $array) {
$name = false;
foreach ($array as $a) {
if ($a[0] == $year) {
$name = $a[1];
break;
}
}
return $name;
}
Usage:
$example; // your array
$n = getNameByYear(1965, $array); // Bob
$n = getNameByYear(1973, $array); // John
$n = getNameByYear(1982, $array); // Paul
$n = getNameByYear('1965', $array); // Bob
$n = getNameByYear('1973', $array); // John
$n = getNameByYear('1982', $array); // Paul
$n = getNameByYear('wrong', $array); // false
$n = getNameByYear(2035, $array); // false

Categories