Combining arrays - PHP - php

I have an array like:
print_r($arr);
array(2) {
["'type'"]=>
array(3) {
[0]=>
string(17) "tell" // <----
[1]=>
string(6) "mobile" // <----
[2]=>
string(6) "address" // <----
}
["'value'"]=>
array(3) {
[0]=>
string(11) "+00.0000000" // tell
[1]=>
string(11) "12345678" // mobile
[2]=>
string(11) "Blah SQ." // address
}
}
I want a final string like:
tell = +00.0000000<br />mobile = 12345678<br />address = Blah SQ.
Now it's been more than an hour I'm struggling with this but no results yet, anyone could help me with this? I would appreciate anykind of help.
Thanks
=======================================
What I have tried:
$arr is an array so I did:
foreach($arr as $values){
// here also $values is an array, so I needed another foreach to access to items:
$i = 0;
foreach($values as $items){
// now making the final output
#$output.= $items['type'][$i] . '=' . $items['value'][$i] . '<br />';
$i++;
}
}

I'd go for array_combine(). Basically it does what you request:
$yourArray = [
"type" => ["tell", "mobile", "address"],
"value" => ["+00.0000000", "12345678", "Blah SQ."]
];
$combined = array_combine($yourArray["type"], $yourArray["value"]);
will be
$combined = [
"tell" =>"+00.0000000",
"mobile" =>"12345678",
"address" =>"Blah SQ."
];
Lastly, you can iterate through that array and then join the values:
$finalArray=array();
foreach($combined as $type=>$value)
$finalArray[]="$type=$value";
$string = join("<br/>", $finalArray); // Will output tell=+00.000000<br/>mobile=12345678<br/>address=Blah SQ.
It's not the fastest method but you'll learn quite a bit about arrays.

EDIT (using array_combine by #Dencker)
foreach($arr as $values) {
// here also $values is an array, so I needed another foreach to access to items:
$v = array_combine($values["'type'"], $values["'value'"]);
foreach($v as $key => $val) {
// now making the final output
$output.= $key . '=' . $val . '<br />';
}
}
Try this
$arr = array(
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+00000', '123123', 'foo')
),
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+10000', '123123', 'bar')
),
array(
"'type'" => array('tell', 'mobile', 'address'),
"'value'" => array('+20000', '123123', 'foobar')
),
);
var_dump($arr);
$output = '';
foreach($arr as $values) {
// here also $values is an array, so I needed another foreach to access to items:
$i = 0;
foreach($values as $items) {
// now making the final output
$output.= $values["'type'"][$i] . '=' . $values["'value'"][$i] . '<br />';
$i++;
}
}
echo $output;
You were referencing the other array in the second loop.
=============================================================
EDIT:
var_dump($arr);
array(3) {
[0]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+00000"
[1]=> string(6) "123123"
[2]=> string(3) "foo"
}
}
[1]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+10000"
[1]=> string(6) "123123"
[2]=> string(3) "bar"
}
}
[2]=> array(2) {
["type"]=> array(3) {
[0]=> string(4) "tell"
[1]=> string(6) "mobile"
[2]=> string(7) "address"
}
["value"]=> array(3) {
[0]=> string(6) "+20000"
[1]=> string(6) "123123"
[2]=> string(6) "foobar"
}
}
}
OUTPUT:
tell=+00000
mobile=123123
tell=+10000
mobile=123123
tell=+20000
mobile=123123

Related

How to get specific values out of all indexes in an array

I have an array which I want to iterate over to push the items into a select box, but I can't figure out how to do it.
The array I get from the function:
array(2) {
["de"]=> array(10) {
["id"]=> int(10)
["order"]=> int(1)
["slug"]=> string(2) "de"
["locale"]=> string(5) "de-DE"
["name"]=> string(7) "Deutsch"
["url"]=> string(34) "http://localhost/werk/Mol/de/haus/"
["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/de.png"
["current_lang"]=> bool(false)
["no_translation"]=> bool(false)
["classes"]=> array(4) {
[0]=> string(9) "lang-item"
[1]=> string(12) "lang-item-10"
[2]=> string(12) "lang-item-de"
[3]=> string(15) "lang-item-first"
}
}
["nl"]=> array(10) {
["id"]=> int(3)
["order"]=> int(2)
["slug"]=> string(2) "nl"
["locale"]=> string(5) "nl-NL"
["name"]=> string(10) "Nederlands"
["url"]=> string(26) "http://localhost/werk/Mol/"
["flag"]=> string(66) "http://localhost/werk/Mol/wp-content/plugins/polylang/flags/nl.png"
["current_lang"]=> bool(true)
["no_translation"]=> bool(false)
["classes"]=> array(4) {
[0]=> string(9) "lang-item"
[1]=> string(11) "lang-item-3"
[2]=> string(12) "lang-item-nl"
[3]=> string(12) "current-lang"
}
}
}
I tried a foreach but I did only get the indexes of the array
<?php
$translations = pll_the_languages(array('raw' => 1));
$lang_codes = array();
foreach ($translations as $key => $value) {
array_push($lang_codes, $key);
}
?>
I need the language slug, URL, and flag from all indexes in this array (de & nl), what should I do?
A simple iteration over the outer array and then pick the values you want from the sub array.
<?php
$translations = pll_the_languages(array('raw' => 1));
$lang_codes = array();
foreach ($translations as $lang => $info) {
$lang_codes[$lang] = [ 'slug' => $info['slug'],
'url' => $info['url'],
'flag' => $info['flag']
];
}
?>
You can approach this as
$res = [];
foreach($translations as $key => $value){
$res[$key] = [
'slug' => $value['slug'],
'url' => $value['url'],
'flag' => $value['flag']
];
}
Live Demo

Combing matched keys in an array

Edited
I get the combined item_ids now, but not the single item_ids.
I have an array with three keys.
$searchArray = {
[0]=> array(3) {
["keyword"]=> string(7) "history"
["url"]=> string(7) "history"
["item_id"]=> string(2) "16"
}
[1]=> array(3) {
["keyword"]=> string(4) "past"
["url"]=> string(4) "past"
["item_id"]=> string(2) "16"
}
[89]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "34"
}
[93]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "35"
}
I want to combine the options that have the same keyword/url.
Just need to check if keyword matches.
The final format needs to be something that jquery autocomplete can accept, where I can assign the text to keyword and the value to url, id to the item_id.
There were only two keys in the array before and I would combine matches this way.
foreach ($searchArray as $row)
{
$combineMatches[ $row['keyword'] ][] = $row['item_id'];
}
result after using json_encode():
"anthropologist":["27","37"],
"biomedical":["34","35"],
"m.s.":["18","19","23"]
What I currently have:
$combineMatches = array();
foreach ($searchArray as $row)
{
$match =
array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id']+= $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array_push($row['item_id'])
]);
}
}
Result:
[7]=> array(3)
{
["keyword"]=> string(8) "theology"
["url"]=> string(8) "theology"
["item_id"]=> NULL
}
[13]=> array(3)
{
["keyword"]=> string(7) "writing"
["url"]=> string(7) "writing"
["item_id"]=> NULL
}
How do I add to the array column of just item_id ? Which I see is a string, but I need as an array.
This gets JSON encoded in the end of the PHP and read by jquery autocomplete.
Thank you for pointing out the string/array issue.
I changed how to add to the third key if there is a match, and if there isn't a match the solution was changing the array_push to just array.
$combineMatches = array();
foreach ($searchArray as $row)
{
$match=array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id'][] = $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array($row['item_id'])
]);
}
}

Count multidimensional array

I have my main array:
array(6) {
[1]=> array(3) {
[0]=> string(15) "Extension"
[1]=> int(1)
[2]=> string(6) "3,00 "
}
[2]=> array(3) {
[0]=> string(32) "Physics "
[1]=> string(1) "1"
[2]=> string(6) "3,00 "
}
[3]=> array(3) {
[0]=> string(31) "Physics "
[1]=> int(1)
[2]=> string(6) "6,00 "
}
[4]=> array(3) {
[0]=> string(34) "Desk"
[1]=> int(4)
[2]=> string(8) "127,00 "
}
[5]=> array(3) {
[0]=> string(18) "assistance"
[1]=> int(1)
[2]=> string(7) "12,50 "
}
[6]=> array(3) {
[0]=> string(15) "Extension"
[1]=> int(1)
[2]=> string(6) "3,00 "
}
}
My expected output is:
Extension 2
Physics 2
Desk 1
Assistance 1
The result must be in an resultarray
How can I do? I tried with array_count_values function but don't work.
How can I stock answear:
I tried this code but It doesn't work
$tabrecap = array();
foreach($counts as $key=>$value){
//echo $key." qte".$value;
$tabrecap = array ($key,$value,$valueOption);
}
As you asked in comment,Please try this:-
<?php
$array = array( '1'=> array('0'=>"Extension", '1'=> 1, '2'=>"3,00 " ), '2'=> array('0'=>"Physics",'1'=>"1","3,00 " ),'3'=> array('0'=>"Physics",'1'=>1,"6,00 "),'4'=> array('0'=>"Desk",'1'=>4,"127,00 "),'5'=> array('0'=>"assistance",'1'=>1,"12,50 " ),'6'=> array('0'=>"Extension",'1'=>1,"3,00 "));
$count = array();
$i = 0;
foreach ($array as $key=>$arr) {
// Add to the current group count if it exists
if (isset($count[$i][$arr[0]])) {
$count[$i][$arr[0]]++;
}
else $count[$i][$arr[0]] = 1;
$i++;
}
print_r($count);
?>
Output:- https://eval.in/379176
Looping is the answer.
<?php
// untested
$counts = Array();
foreach( $array as $subArray ){
$value = $subArray[0];
$counts[ $value ] = ( isset($counts[ $value ]) )
? $counts[ $value ] + 1
: 1;
}
var_dump( $counts);
Just make a loop and use first item of each array as key :
$array = array(
array("Extension", 1, "3,00"),
array("Physics", "1", "3,00"),
array("Physics", 1, "6,00 ")
);
$count = array();
foreach($array as $a)
$count[$a[0]]++;
var_dump($count); // array(2) { ["Extension"]=> int(1) ["Physics"]=> int(2) }

Group array row data by two columns creating a new 3-level structure

I have 1 arrays:
array(5) { // This is the keys on the CSV.
[0]=>
array(4) {
[0]=>
string(4) "user"
[1]=>
string(4) "date"
[2]=>
string(3) "md5"
[3]=>
string(4) "sha1"
}
[1]=>
array(4) {
[0]=>
string(4) "user1"
[1]=>
string(8) "02/02/15"
[2]=>
string(6) "123456"
[3]=>
string(5) "54321"
}
[2]=>
array(4) {
[0]=>
string(4) "user1"
[1]=>
string(8) "02/03/15"
[2]=>
string(6) "123456"
[3]=>
string(5) "54321"
}
[3]=>
array(4) {
[0]=>
string(5) "user2"
[1]=>
string(8) "02/02/15"
[2]=>
string(6) "112233"
[3]=>
string(6) "332211"
}
[4]=>
array(4) {
[0]=>
string(5) "user2"
[1]=>
string(8) "02/03/15"
[2]=>
string(6) "112244"
[3]=>
string(6) "332244"
}
}
So User 1 and User 2 each have a file that is MD5/SHA1 sum'd and checked.
I would like the data to turn from the above, to this:
array(3) {
["user"]=>
array(1) {
["date"]=>
array(2) {
[0]=>
string(3) "md5"
[1]=>
string(4) "sha1"
}
}
["user1"]=>
array(1) {
["02/02/15"]=>
array(2) {
[0]=>
string(6) "123456"
[1]=>
string(5) "54321"
}
["02/03/15"]=>
array(2) {
[0]=>
string(6) "123456"
[1]=>
string(5) "54321"
}
}
["user2"]=>
array(1) {
["02/02/15"]=>
array(2) {
[0]=>
string(6) "112233"
[1]=>
string(6) "332211"
}
["02/03/15"]=>
array(2) {
[0]=>
string(6) "112244"
[1]=>
string(6) "332244"
}
}
}
So far, I'm close. Here is my code:
<?php
error_reporting(E_ALL & ~E_NOTICE);
//Reading csv
$csv = array_map('str_getcsv',file('/var/www/sums.csv'));
debug($csv);
//User list
$userData = array();
foreach ($csv as $user) {
$ts = $user[1];
$un = $user[0];
$sums = array($user[2],$user[3]);
$userPreProc[$un] = array($ts => $sums);
$userData = array_merge($userPreProc, $userData);
}
debug($userData);
function debug($db) {
echo "<pre>";
var_dump($db);
echo "</pre>";
}
?>
The issue here is that only the first 'user1' and 'user2' entries are merged to the new array, so it looks like this:
array(3) {
["user"]=>
array(1) {
["date"]=>
array(2) {
[0]=>
string(3) "md5"
[1]=>
string(4) "sha1"
}
}
["user1"]=>
array(1) {
["02/02/15"]=>
array(2) {
[0]=>
string(6) "123456"
[1]=>
string(5) "54321"
}
}
["user2"]=>
array(1) {
["02/02/15"]=>
array(2) {
[0]=>
string(6) "112233"
[1]=>
string(6) "332211"
}
}
}
Any suggestions how I can ensure that all the keys are merged as expected?
Just shift off the first two elements and use those respective values as the first and second level keys.
Code: (Demo)
$result = [];
foreach ($array as $row) {
$result[array_shift($row)][array_shift($row)] = $row;
}
var_export($result);
Or use array destructuring in the foreach declaration: (Demo)
$result = [];
foreach ($array as [$user, $date, $md5, $sha1]) {
$result[$user][$date] = [$md5, $sha1];
}
var_export($result);
Just change your foreach loop to be like this. You don't need to merge your array via function.
foreach ($csv as $user) {
$ts = $user[1];
$un = $user[0];
$sums = array($user[2],$user[3]);
$userData[$un][$ts] = $sums;
}

Group same array values inside object into same keys

I have the array below:
[1]=>
array(2) {
[0]=>
object(stdClass)#23 (7) {
["AddressesTableID"]=> string(1) "8"
["AccreditNo"]=> string(13) "5129876de28ff"
["Type"]=> string(4) "home"
["Street"]=> string(34) "Wallace, Village, Under the bridge"
["Municipality"]=> string(8) "Tortuous"
["Province"]=> string(8) "Sardonic"
["ContactNo"]=> string(8) "92012010"
}
[1]=>
object(stdClass)#24 (7) {
["AddressesTableID"]=> string(1) "9"
["AccreditNo"]=> string(13) "5129876de28ff"
["Type"]=> string(6) "office"
["Street"]=> string(25) "Rasputin Query, Palpitate"
["Municipality"]=> string(7) "Opulent"
["Province"]=> string(6) "Number"
["ContactNo"]=> string(8) "29101011"
}
}
Can you guys help me on how to transform this into:
Where all the values are grouped as an array into similar keys?
["AccreditNo"]=> array(2) { "5129876de28ff", "GKIJUGUIKGI" }
["Type"]=> array(2) { "home", "home" }
["Street"]=> ...
["Municipality"]=> ...
["Province"]=> ...
["ContactNo"]=> ...
Try with:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $data ) {
foreach ( $data as $key => $value ) {
if ( !isset($output[$key]) ) {
$output[$key] = array();
}
$output[$key][] = $value;
}
}
You can use the array_merge_recursive() function, as follows:
$arr = array_merge_recursive($arr1, $arr2)
for more information, please see here:http://www.php.net/manual/en/function.array-merge-recursive.php

Categories