Mergin two arrays but keep indexes - php

So I have these two arrays that I need to merge into one and keep the indexes. I tried different things like array_merge, array_merge_recursive, etc but I couldn't figure it out.
array(3) {
[0]=>
string(4) "Peter"
[1]=>
string(4) "Josh"
[2]=>
string(4) "Jasper"
}
array(3) {
[0]=>
string(2) "18"
[1]=>
string(2) "19"
[2]=>
string(2) "25"
}
This is how I want it to look like:
array(3) {
[0]=>
array(2) {
["name"]=>
string(5) "Peter"
["age"]=>
int(18)
}
[1]=>
array(2) {
["name"]=>
string(4) "Josh"
["age"]=>
int(19)
}
}
Any ideas how I can achieve this?

Try This:
$array1 = array(0 => 'Peter', 1 => 'Josh', 2 => 'Jasper');
$array2 = array(0 => '18', 1 => '19', 2 => '25');
for($i = 0; $i<count($array1); $i++){
$newArray[] = array("name" => $array1[$i], "age" => $array2[$i]);
}
var_dump($newArray);

This is something I've used before as more reusable decision in case you want to add for example not only Name, Age, but Email or something else later.
Posting below code with explained comments.
<?php
// Array containing names
$namesArr = array(
'Peter',
'Josh',
'Jasper'
);
// Array containing ages
$agesArr = array(
18,
19,
25
);
$arrayDesign = array(
'name' => $namesArr,
'age' => $agesArr
);
/**
* Combines given array design into one grouped by keys.
* Example Input:
* $design => array(
* 'name' => array('Name1', 'Name2'),
* 'age' => array(10, 20)
* );
* Example Output:
* $output => array(
* 0 => array(
* 'name' => 'Name1',
* 'age' => 10
* ),
* 1 => array(
* 'name' => 'Name2',
* 'age' => 20
* )
* );
*
* #param Array $arrayDesign
*
* #return Array combined array
*/
function combineArraysByKeys($arrayDesign) {
// Holds results
$results = array();
// Get size of first element from the design, so we'll know the size of rest elements.
$designElementSize = count($arrayDesign[array_keys($arrayDesign)[0]]);
// Count from-to elements
for($c = 0; $c < $designElementSize; $c++) {
// Define array as part of results to be added after population
$arrayPart = array();
// Loop thru all keys and get values
foreach(array_keys($arrayDesign) as $key) {
// Assign value to key
$arrayPart[$key] = $arrayDesign[$key][$c];
}
// Add to results array
$results[] = $arrayPart;
}
return $results;
}
$result = combineArraysByKeys($arrayDesign);
echo "<PRE>";
print_r($result);
die();

Related

Multi-dimentional array how to get the nested value without foreach loop

I got output from one of the WordPress table cells. The following value is displayed.
$allcoinkey=get_option('_transient_mcw-custom-data');
var_dump($allcoinkey);
and the output:
[0]=>
array(2) {
["slug"]=>
string(7) "bitcoin"
["keywords"]=>
string(30) "بیتکوین,بیت کوین"
}
[1]=>
array(2) {
["slug"]=>
string(8) "ethereum"
["keywords"]=>
string(27) "اتریوم,اتاریوم"
}
}
How do I access keyword values where slug=bitcoin without foreach?
i use this sample code:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
You can do it like this:
<?php
$allcoinkey = [
[
'slug' => 'bitcoin',
'keywords' => 'بیتکوین,بیت کوین',
],
[
'slug' => 'ethereum',
'keywords' => 'اتریوم,اتاریوم',
],
];
$bitcoinKeywords = current(array_filter($allcoinkey, static function (array $cryptoCurrency) {
return $cryptoCurrency['slug'] === 'bitcoin';
}))['keywords'];
echo $bitcoinKeywords;

array_combine results only one result [duplicate]

This question already has answers here:
array_combine is return only last value
(2 answers)
Closed 3 years ago.
I am using the following code to get two arrays into one json result. But getting only the first index as result. Is there any error in the code or anybody can suggest an alternate method to get the same result.
$array1 = $_POST['array1'];
$array2 = $_POST['array2'];
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('name' => $name, 'value' => $value);
}
echo $json = json_encode($jsonArray);
$_POST['array1'] = array(4) {
[0]=>
string(3) "day1"
[1]=>
string(3) "day2"
[2]=>
string(3) "day3"
[3]=>
string(3) "day4"
}
$_POST['array2'] = array(4) {
[0]=>
string(3) "item1"
[1]=>
string(3) "item2"
[2]=>
string(3) "item3"
[3]=>
string(3) "item4"
}
Expected result should be like
[{"name":"day1","value":"item1"},{"name":"day2","value":"item2"},{"name":"day3","value":"item3"}]
Try this,
$arr1 = array('0' => 'day1', '1' => 'day2', '2' => 'day3', '3' => 'day4');
echo'<pre>';print_r($arr1);
$arr2 = array('0' => 'item1','1' => 'item2','2' => 'item3','3' => 'item4');
echo'<pre>';print_r($arr2);
echo'<pre>';print_r(array_combine($arr1, $arr2));
$newArray = array();
foreach(array_combine($arr1, $arr2) as $key => $value){
array_push($newArray, array('name'=> $key,'value'=>$value));
}
echo'<pre>';print_r($newArray);
echo json_encode($newArray);die;

How can I print the lowest key of an array?

This is my array:
array(4) {
["1"]=>
array(3) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
[2]=>
string(2) "03"
}
["2"]=>
array(2) {
[0]=>
string(2) "01"
[1]=>
string(2) "02"
}
["3"]=>
array(1) {
[0]=>
string(2) "01"
}
["4"]=>
array(1) {
[0]=>
string(2) "01"
}
}
I want to print the lowest key, but only from the keys, that have less than 3 values.
echo min(array_keys($myarray));
gives me the result: 1
But key 1 already has 3 values, so the result I would need is 2. In the case every key has 3 values then print the next key (in this case would be 5)
I do not know how to do this. I am happy for every hint or advise.
This function iterate over your array and looks for all keys that has a value less then 3 values. It will return the first it founds if none is found the next key is return.
function getLowestKeyWithLessThan($yourArray, $number=3)
{
foreach ($yourArray as $key => $value) {
if (count($value) < $number)
return $key;
}
return count($yourArray) + 1;
}
If I run the following lines:
print "Answer " . getLowestKeyWithLessThan($yourArray);
print "\nAnswer " . getLowestKeyWithLessThan($AllKeysHasThreeElements);
This gives the answer:
Answer 2
Answer 5
Here is the data I used to test this:
$yourArray = array(
"1"=> array(
'0' => "01",
'1' => "02",
'2' => "03",
),
"2"=> array(
'0' => "01",
'1' => "02",
),
"3"=> array(
'0' => "01",
),
"4"=> array(
'0' => "01",
),
);
$threeValues = array(
'0' => "01",
'1' => "02",
'2' => "03",
);
$AllKeysHasThreeElements = array(
"1"=> $threeValues,
"2"=> $threeValues,
"3"=> $threeValues,
"4"=> $threeValues,
);
Of course the data could also been written like this:
$threeValues = array("01", "02", "03");
$yourArray = array($threeValues, array("01", "02"), array("01"), array("01"));
$AllKeysHasThreeElements = array($threeValues,$threeValues,$threeValues,$threeValues);

Can't declare keys in two dimensional array in PHP

When i try to generate array, like this way:
$files_array = array(
'name' => array(),
'path' => array()
);
and then assign them values:
$files_array['name'][] = $fileinfo->getFilename();
$files_array['path'][] = $pathname;
the var_dump() function return me an array with numeric keys instead of "name" and "path", like this:
array(2) { [0]=> array(0) { } [1]=> array(0) { } }
What's wrong with the array? I've tried several way of doing this, but none give me my desired array.
EDIT:
A filled array dump, with the same code:
array(2) { [0]=> array(3) { [0]=> string(44) "./upload/4//lol/Nuovo documento di testo.TXT" [1]=> string(51) "./upload/4//lol/blue_bokeh_4-wallpaper-1366x768.jpg" [2]=> string(29) "./upload/4//lol/menny €.txt" } [1]=> array(3) { [0]=> string(28) "Nuovo documento di testo.TXT" [1]=> string(35) "blue_bokeh_4-wallpaper-1366x768.jpg" [2]=> string(13) "menny €.txt" } }
EDIT:
My full code
$files_array = array(
'name' => array(),
'path' => array()
);
$fileinfos = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootpath)
);
foreach ($fileinfos as $pathname => $fileinfo) {
if (!$fileinfo->isFile())
continue;
$files_array['name'][] = $fileinfo->getFilename();
$files_array['path'][] = $pathname;
}
That's how it works:
<?php
$files_array = array();
$i = 0;
$files_array[$i]['name'] = $fileinfo->getFilename();
$files_array[$i]['path'] = $pathname;
$i++;
The result output will be like:
array (size=2)
0 =>
array (size=2)
'name' => string 'file' (length=4)
'path' => string '/foo/' (length=5)
1 =>
array (size=2)
'name' => string 'file2' (length=5)
'path' => string '/bar/' (length=5)
I would suggest reading the php manual on arrays. Here are some examples.
//1
$files_array = array();
$files_array['name'] = array();
$files_array['path'] = array();
//2
$files_array = array(
'name' => [],
'path' => []
);

Combining two arrays with unique field

Combining A array and B array and want the result show below
EDITED
a = {
[0]=> array(2) {
["pid"]=> string(1) "1"
["val1"]=> string(1) "1"
}
[1]=> array(2) {
["pid"]=> string(2) "12"
["val1"]=> string(1) "1"
}
[2]=> array(2) {
["pid"]=> string(2) "13"
["val1"]=> string(2) "79"
}
}
b = {
[0]=> array(2) {
["pid"]=> string(1) "1"
["val2"]=> string(1) "1"
}
[1]=> array(2) {
["pid"]=> string(2) "12"
["val2"]=> string(1) "1"
}
[2]=> array(2) {
["pid"]=> string(2) "13"
["val2"]=> string(2) "79"
}
[3]=> array(2) {
["pid"]=> string(2) "61"
["val2"]=> string(1) "1"
}
[4]=> array(2) {
["pid"]=> string(2) "62"
["val2"]=> string(2) "24"
}
}
Need help.
If this is coming from a data source, see if there's a way you can do this outside of PHP (e.g. MySQL's JOIN).
If PHP is your only answer, then below is a solution. Note that I changed the values of val1 and val2 so it was a bit more distinguishable.
You must have some sort of grouping constraint, which is configurable in the script below via $groupByKey. Judging by the common occurrence of PID, I assumed this as the subject key.
Also, if you have more than two arrays all following a similar schema (I have commented out $c as an example), you simply add more arguments to array_merge.
The idea is to keep merging each item in the cumulative list by using a fixed key as a "pointer," if you will.
<?php
$a = array(
array('pid' => 1, 'val1' => 'alpha'),
array('pid' => 3, 'val1' => 'bravo'),
array('pid' => 4, 'val1' => 'charlie')
);
$b = array(
array('pid' => 3, 'val2' => 'delta'),
array('pid' => 5, 'val2' => 'echo'),
array('pid' => 1, 'val2' => 'foxtrot'),
array('pid' => 8, 'val2' => 'golf')
);
/*
$c = array(
array('pid' => 3, 'val3' => 'hotel'),
array('pid' => 5, 'val1' => 'india'),
array('pid' => 1, 'val3' => 'juliette'),
array('pid' => 8, 'val3' => 'kilo')
);
*/
$groupByKey = 'pid'; // this becomes the fixed key
$merged = array_merge($a,$b); // array_merge($a,$b,$c); // cumulative container of all items in every subject array
$result = array(); // the result will be stored here, e.g. a temporary "table"
foreach ( $merged as $item ) { // $merged is essentially a table of subjects and $item is each row
if ( !isset($result[$item[$groupByKey]]) ) { // if we haven't come across this key yet
$result[$item[$groupByKey]] = array(); // initialize it
}
$result[$item[$groupByKey]] = array_merge($result[$item[$groupByKey]],$item); // consolidate all the cells for this row, later duplicate keys will cause values to be replaced
}
$result = array_values($result); // normalize the result keys, for the view they should increment rather than represent the group-by subjects
var_dump($result); // let's see how we did
?>
Provides:
array (size=5)
0 =>
array (size=3)
'pid' => int 1
'val1' => string 'alpha' (length=5)
'val2' => string 'foxtrot' (length=7)
1 =>
array (size=3)
'pid' => int 3
'val1' => string 'bravo' (length=5)
'val2' => string 'delta' (length=5)
2 =>
array (size=2)
'pid' => int 4
'val1' => string 'charlie' (length=7)
3 =>
array (size=2)
'pid' => int 5
'val2' => string 'echo' (length=4)
4 =>
array (size=2)
'pid' => int 8
'val2' => string 'golf' (length=4)

Categories