I know that this is asked few times here but there is an advanced problem.
I got an array $data and I need to got this structure when foreach
$data[0] => [
'value1' => string(x) "some data",
'value2' => string(x) "some other data"
];
$data[1] => ... ...
I know that can't execute array_push with array keys also tried code bellow but I got two big arrays. I just need one big array with small sub arrays
My Code
$authors['email'] = array();
$authors['name'] = array();
foreach (json_decode($response)->response->docs AS $docs)
{
$articleAuthors = explode(', ', $docs->authors);
$i=0;
foreach ($docs->email as $email) {
array_push($authors['email'], $email);
array_push($authors['name'], $articleAuthors[$i]);
++$i;
}
}
Try this, to get one array with little subarrays
$authors = array();
#...
foreach($docs->email as $email){
array_push($authors, array('email'=>$email,'name'=>$articleAuthors[$i]));
++$i;
}
#...
I just find solution, code above is makeing two big arrays and just added line bellow.
$authors['email'] = array();
$authors['name'] = array();
foreach (json_decode($response)->response->docs AS $docs)
{
$articleAuthors = explode(', ', $docs->authors);
$i=0;
foreach ($docs->email as $email) {
array_push($authors['email'], $email);
array_push($authors['name'], $articleAuthors[$i]);
++$i;
}
}
$data = array_combine($authors['name'], $authors['email']);
Related
I'm trying to write a function that do the following :
Let's say i have an array :
$data = array(
array('10','15','20','25'),
array('Blue','Red','Green'),
array('XL','XS')
)
and my result array should be like :
$result = array(
array('10','15','20','25'),
array('Blue','Red','Green','Blue','Red','Green','Blue','Red','Green','Blue','Red','Green')
array('XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS')
)
Im stuck with this because i want a function that is able to do this no matter how much array there is in the first array $data
I have only been able to write this, which is what give the $result array :
foreach($data[2] as $value2){
$result[2][] = $value2;
foreach($data[1] as $value1){
$result[1][] = $value1;
foreach($data[0] as $value0){
$result[0][] = $value0;
}
}
}
After a few research, it seems that a recursive function is the way to go in order to dynamically generate those foreach but i can't get it to work.
Thanks for your help.
This is dynamic:
$result[] = array_shift($data);
foreach($data as $value) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
Get and remove the first element from original
Loop remaining elements and fill result with values X number of values in first element
Since the elements were arrays merge them all into result
If modifying the original is unwanted, then use this method:
$result[] = reset($data);
while($value = next($data)) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
just use array_fill and array_merge functions
$result = array(
$data[0],
array_merge(...array_fill(0,count($data[0]), $data[1])),
array_merge(...array_fill(0,count($data[0])*count($data[0]), $data[2]))
);
print_r($result);
demo on eval.in
I have inbound return data -> http://php.net/manual/en/function.json-decode.php that is in PhP array format. The file data is the same type. It is just $result from the previous cycle.
$result = api_query("mytrades", array("marketid" => $id));
How do I compare $result array with $file array and then over write FILE with $result data?
In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
I tried array_diff but it does not like my data types and I cannot find a work around.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = 155;
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result, $lines);
var_dump($result);
file_put_contents('myDB.db', print_r($result, true));
?>
var_dump($result);
I think, you looking for some serialization, json_encoding for example.
$result = array(
'return' => array(
array(
"tradeid" =>"74038377",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"197009493",
),
array(
"tradeid" =>"2",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"2",
)
)
);
function getdiff($new, $old)
{
//implement right logical diff here
$diff = array();
$old_serialized = array();
foreach ($old as $item) {
$old_serialized[] = json_encode($item);
}
foreach ($new as $item) {
if (in_array(json_encode($item), $old_serialized)) {
continue;
}
$diff[] = $item;
}
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff($result['return'], $old);
file_put_contents('1.db', json_encode($result['return']));
print_r($arrayDiffresult);
I can't seem to figure this out and I'm hoping someone has a magical recursive solution to this. I have a list of keys and basically I want to transform it into a nested array.
array('level1', 'level2', 'level3');
To
array(
'level1' => array(
'level2' => array(
'level3' // last key in array should be just a value
)
)
)
Much appreciation to anyone who can help!
Something like this should do the job:
function buildMultiDimensional(Array $arr)
{
// the first value will become a new key
$newKey = array_shift($arr);
if (empty($arr)) {
// this is where the recursion stops
return $newKey;
}
// and the recursion !!!
return array($newKey => buildMultiDimensional($arr));
}
$arr = array('level1', 'level2', 'level3', 'level4', 'level5');
var_dump(buildMultiDimensional($arr));
The result is what's expected:
array(1) {
["level1"]=>
array(1) {
["level2"]=>
array(1) {
["level3"]=>
array(1) {
["level4"]=>
string(6) "level5"
}
}
}
}
You don't need recursion. A single loop is fine with references.
<?php
//array to iterate
$array = array('level1', 'level2', 'level3');
//contains our entire array
$out = array();
//temp variable to store references as we go down.
$tmp = &$out;
//get the last value off the array
$last = array_pop($array);
//loop over the array
foreach($array as $level){
//make an array under the current level
$tmp[$level] = array();
//assign tmp to the new level
$tmp = &$tmp[$level];
}
//assign the last key as the value under the last key
$tmp = $last;
//display output
print_r($out);
example: http://codepad.viper-7.com/zATfyo
And without references, working in reverse:
<?php
//array to iterate
$array = array('level1', 'level2', 'level3');
//get the last value off the array
$out = array_pop($array);
//flip the array backwards
$array = array_reverse($array);
//loop over the array
foreach($array as $level){
$out = array($level=>$out);
}
//display output
print_r($out);
Example: http://codepad.viper-7.com/fgxeHO
I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}
I'm having some trouble understanding the coding in PHP, when it comes to multidimensional arrays and how to push.
The idea is to push a "Attribute" and a "Attribute value"
I have tried the formula below
$i = 0;
$array = array();
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[] = ($strAtt => $strVal);
The $array[] = ($strAtt => $strVal); doesnt give me much success.
I have tried array_push($array, $strAtt => $strVal) - no luck..
As an extra questions, how do I loop trough the array and print me multidimensional values ?.
NEW CODE
while ($z->name === 'RECORD')
{
$node = new SimpleXMLElement($z->readOuterXML());
$Print = FALSE;
$output = "";
$i = 0;
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[$strAtt] = $strVal;
if(($i == 6) && ($node->PROP[$i]->PVAL == $ProductLookup))
{
$Print = TRUE;
$Product = $node->PROP[$i]->PVAL;
}
$i++;
}
if($Print == TRUE) {
echo $output;
echo "Product : ".$Product."<br>";
var_dump($array);
}
//print_r($array);
$print = FALSE;
// go to next <product />
$z->next('RECORD');
}
New code added. For some reason my $array is totally empty when i dump it, although my $Output is full of text ?
It sounds like you are wanting an "associative" array and not necessarily a multi-dimensional array. For associative arrays you don't use array_push. Just do this:
$array[$strAtt] = $strVal;
Then to loop the array just do this:
foreach ($array as $key => $value) {
echo "$key = $value\n";
}
Go through array in php , you will understand how array works in php.
Besides if you want to add an element to a multidimensional array you can achieve like this :
$node = array ("key1"=> array (a,b) , "key2"=> array (c,d));
$array = array();
foreach ($node as $key=>$value) {
$array [$key] = $value;
}
This will be the resulting $array after the loop :
array (
"key1"=> array (
a,b
) ,
"key2"=>
array (c,d)
)
Hope that helps , happy coding :)