PHP multiple arrays to one associative array - php

How can I merge this three arrays
$name ={"Tom", "John", "David"};
$v1 = {"Tom":100, "David":200};
$v2 = {"John":500, "Tom":400};
into one multidimensional associative array in two different ways?
One way is the key order should be same as that of array "name".
$name_merged_original_order = array (
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
"John" => Array(
"v1" => "N/A",
"v2" => 500
),
"David" => Array(
"v1" => 100,
"v2" => "N/A"
)
)
Another ways is the alphabetical of array "name":
$name_merged_asc = array (
"David" => Array(
"v1" => 100,
"v2" => "N/A"
),
"John" => Array(
"v1" => "N/A",
"v2" => 200
),
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
)
The tricky part is that array "v1" and "v2" is not ordered as the key of "name." They also don't have all keys as in "name." Thanks!

It's not tested and the easiest solution:
$name_merged_original_order = array();
foreach($name as $key){
$name_merged_original_order[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_original_order[$key]['v1'] = $v1[$key];
}
else{
$name_merged_original_order[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_original_order[$key]['v2'] = $v2[$key];
}
else{
$name_merged_original_order[$key]['v2'] = 'N/A';
}
}
sort($name);
$name_merged_asc = array();
foreach($name as $key){
$name_merged_asc[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_asc[$key]['v1'] = $v1[$key];
}
else{
$name_merged_asc[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_asc[$key]['v2'] = $v2[$key];
}
else{
$name_merged_asc[$key]['v2'] = 'N/A';
}
}

As I understand you would like something like that:
$name = array("Tom", "John", "David");
$result = array();
$v1 = array("Tom" => "200", "John" => "100", "David" => "10");
$v2 = array("Tom" => "254", "David" => "156");
$vars = array("v1", "v2");
foreach($name as $n)
{
$result[$n] = array();
foreach($vars as $v)
{
if(array_key_exists($n, ${$v}))
$result[$n][$v] = ${$v}[$n];
}
}
I hope $result is what you need.

For Example, you have these arrays:
<?php
$FirstArrays = array('a', 'b', 'c', 'd');
$SecArrays = array('1', '2', '3', '4');
1)
foreach($FirstArrays as $index => $value) {
echo $FirstArrays[$index].$SecArrays[$index];
echo "<br/>";
}
or 2)
for ($index = 0 ; $index < count($FirstArrays); $index ++) {
echo $FirstArrays[$index] . $SecArrays[$index];
echo "<br/>";
}

Assume from your comments you only want items that match in all 3 arrays:
for( $i=0; $i< count($name) ; $i++){
if( !empty( $v1[ $name[$i]]) && !empty( $v2[ $name[$i]]) ){
$newArray[$name[$i]]= array( 'v1'=> $v1[ $name[$i]], 'v2'=> $v2[ $name[$i]]):
}
}
To sort:
asort($newArray);

Related

Divide numbers in 2 multidimensional array

I have 2 sets of multidimensional array ($profit & $sales). I want to divide the numbers in 2 multidimensional array to get the % of margin (using this formula: $profit/$sales*100)
$profit= array(
0 => array(
"no"=> "1",
"value"=>"10"
),
1=> array(
"no"=> "2",
"value"=>"15"
)
);
$sales= array(
0 => array(
"no"=> "1",
"value"=>"100"
),
1=> array(
"no"=> "2",
"value"=>"200"
)
);
This is the expected output:
$margin= array(
0 => array(
"no"=> "1",
"value"=>"10"
),
1=> array(
"no"=> "2",
"value"=>"7.5"
)
);
I have done some search with no luck still, below is the function that I'm using, it is not working:
function ArrayDivide($arrayList = [])
{
$m = [];
$no_details = [];
$i = 0;
foreach ($arrayList as $arrayItem) {
foreach ($arrayItem as $subArray) {
if (isset($no_details[$subArray['x']])) {//if no is exist
$m[$no_details[$subArray['x']]]['y'] = $m[$no_details[$subArray['x']]]['y'] /$subArray['y']*100;
} else {
$no_details[$subArray['x']] = $i;
$m[$i] = ["x"=>$subArray['x'], "y"=>"0"];
$i++;
}
}
}
return $m;
}
How you done similar function before? Where should I fix?
Thanks.
Use "Sourcey86" code and replace:
$res = $value / $no;
to
$res = $value/$sales[$key]['value']*100;
(I don't have enough points to add a comment on his post :D )
Something like this ? If I understood your question correctly.
function getMargin($profit, $sales){
$margin = [];
foreach($profit as $key => $val){
$no = $val['no'];
$value = $val['value'];
if(isset($sales[$key]) && $sales[$key]['no'] == $no){
$res = ($value/$sales[$key]['value'])*100;
$margin[$key]['no'] = $no;
$margin[$key]['val'] = $res;
}
}
return $margin;
}
var_dump(getMargin($profit, $sales));

PHP foreach returning last row in multidimentional array

I am trying get user value from multidimensional array as
$array = array();
$array["id"] = "1";
$array["name"] = "name1";
$array["country"] = "country1";
$array["id"] = "2";
$array["name"] = "name2";
$array["country"] = "country2";
$array["id"] = "3";
$array["name"] = "name3";
$array["country"] = "country3";
$array["id"] = "4";
$array["name"] = "name4";
$array["country"] = "country4";
foreach($array as $e){
print_r($e);
}
It return me 4name4country4 only
I need to fetch rows like
foreach($array as $e){
$id=$e['id'];
$name=$e['name'];
$country=$e['country'];
echo $id.'/'.$name.'/'.$country.'<br>';
}
but this gives me error as Illegal string offset 'id'
from what I understood about array this should return all values, Please see why this simple array is not working and suggest any way to do it
Currently you are overwriting the keys. Need to add the keys properly. You have to build the array like -
$array[0]["id"] = "1";
$array[0]["name"] = "name1";
$array[0]["country"] = "country1";
$array[1]["id"] = "2";
$array[1]["name"] = "name2";
$array[1]["country"] = "country2";
OR
$array = array(
0 => array('id' => 1, 'name' => 'name1', 'country' => 'country1'),
1 => array('id' => 2, 'name' => 'name2', 'country' => 'country2'),
);
Instead, do it like so you won't have to give array keys manually
$array = array();
$array[] = array("id" => 123, "name" => "Your name", "country" => "UK");
$array[] = array("id" => 1342, "name" => "Your name 2 ", "country" => "UK");
then in foreach do this
foreach($array as $key => $val){
echo $key. ": ".$val['id']. " " . $val['name'];
}
You have to create the multidimensional array like this, right now you're overwriting the array multiple times.
$arrays = [
[0]=>
["id"] => "1",
["name"] => "name1",
["country"] => "country1"
],
[1]=>[
...
]
];
foreach($arrays as $array){
$id=$array['id'];
$name=$array['name'];
$country=$array['country'];
echo $id.'/'.$name.'/'.'$country'.'<br>';
}

Create an array with dynamic input in PHP

I have to create a array dynamically like I have a method which will pass keys and based on those keys I need to create arrays inside them
Format will be like-
{
"TEST1":{
"140724":[
{
"A":"1107",
"B":4444,
"C":"1129",
"D":"1129"
},
{
"A":"1010",
"B":2589,
"C":"1040",
"D":"1040"
}
],
"140725":[
]
}
}
So how should I frame this logic inside for loop. I am new to php so formatting the same creating trouble.
$json_Created = array("TEST1" => array());
foreach($val as $key=>$value){
array_push($json_created,array($key = array()));
}
The entire array is dynamic, so like I have 140724 ,,, till 140731 (actually date format yymmdd), any amount if numbers can be considered. SO that part is dynamic moreover some dates may be wont have any values and some will have.
So my main point is to develop that logic so that irrespective the
number of inputs , my array formation must be intact.
You can use json_encode with array to do so
$array = array(
"TEST1" => array(
"140724" => array(
array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
),
array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
)
),
"140725" => array(
)
)
);
echo json_encode($array);
Another way to construct array is
$array = array();
$array["TEST1"]["140724"][] = array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
);
$array["TEST1"]["140724"][] = array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
);
$array["TEST1"]["140725"] = array();
echo json_encode($array);
Finally managed to write the code-
$keys_content = array("starttime", "id", "duration", "endtime");
$dates = array();//140724,140725,140726140727
$mainID =“TEST1”;
$arraySuperMain = array();
$arrayMain = array();
for ($j = 0; $j < count($dates); $j++) {
$array_main = array();
$subset = array();
for ($i = 0; $i < count($keys_content); $i++) {
$key = $keys_content[$i];
$subset = array_push_assoc($subset, $key, "Value".$i);
}
$array_main = array_push_assoc($array_main, $dates[$j], $subset);
array_push($arrayMain, $array_main);
}
$createdJSON = array_push_assoc($arraySuperMain, $mainID, $arrayMain);
public static function array_push_assoc($array, $key, $value) {
$array[$key] = $value;
return $array;
}

Find value in multidimensional array by another key and value

I have the following array:
$array = array(
'item-img-list' => array(
array(
'image-type' => 1,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 2,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 3,
'image-url' => 'http://img07.allegroimg.pl/...'
)
)
)
How to get first 'image-url' value where 'image-type' = '2'?
I'm trying do that by this code but nothing:
$zdjecia = $item['item-img-list'];
foreach($zdjecia as $zdjecie) {
foreach($zdjecie as $key=>$value) {
if($key == "image-type" && $value == "2") {
$zdjecie_aukcji = $key['image-url'];
}
}
}
Thank you for any kind of help!
Works!
$searchKey = 2;
foreach($zdjecia as $zdjecie) {
if (**$zdjecie->{'image-type'}** == $searchKey){
$zdjecie_aukcji = **$zdjecie->{'image-url'}**;
break;
}
}
$zdjecia = $item['item-img-list'];
$searchKey = 2;
foreach($zdjecia as $zdjecie) {
if ($zdjecie['image-type'] == $searchKey)
$zdjecie_aukcji = $zdjecie['image-url'];
break;
}
}
or (PHP >=5.5)
$zdjecia = $item['item-img-list'];
$searchKey = 2;
$results = array_column(
$zdjecia,
'image-url',
'image-type'
);
$zdjecie_aukcji = $results[$searchKey];
foreach($zdjecia as $zdjecie) {
foreach($zdjecie as $key=>$value) {
if($key == "image-type" && $value == "2") {
$zdjecie_aukcji = $zdjecie['image-url'];
}
}
}
A suggestions with custom function that I use for my project to find a value by key in multidimensional array:
function array_search_multi($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, array_search_multi($subarray, $key, $value));
}
return $results;
}
Usage:
$results = array_search_multi($array, 'image-type', '2');
echo $results[0]['image-url'];
Output:
http://img07.allegroimg.pl/...
Working example
why not simply this:-
$array = array(
'item-img-list' => array(
array(
'image-type' => 1,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 2,
'image-url' => 'http://img07.allegroimg.pl/...'
),
array(
'image-type' => 3,
'image-url' => 'http://img07.allegroimg.pl/...'
)
)
);
$newArray = array();
foreach($array['item-img-list'] as $k=>$v){
$newArray[$v['image-type']] = $v['image-url'];
}
Output :-
Array
(
[1] => http://img07.allegroimg.pl/...
[2] => http://img07.allegroimg.pl/...
[3] => http://img07.allegroimg.pl/...
)
or
echo $newArray[2];
you can also check key like this:
if (array_key_exists(2, $newArray)) {
// Do whatever you want
}
Working Demo
Add break; right after
$zdjecie_aukcji = $key['image-url'];
modify to:
$zdjecia = $array['item-img-list'];
foreach($zdjecia as $zdjecie) {
if($zdjecie['image-type'] == '2') {
$zdjecie_aukcji = $zdjecie['image-url'];
}
}

Get array's key recursively and create underscore separated string

Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}

Categories