How do I loop through multidimensional JSON array in PHP? - php

I want to write code to loop through a multidimensional array (4 or 5 deep) and echo all keys and values found and skip empty arrays.
$drugs = fopen("http://dgidb.org/api/v2/interactions.json?drugs=FICLATUZUMAB", "r");
$json_drugs = stream_get_contents($drugs);
fclose($drugs);
$data_drugs = json_decode($json_drugs,true);
foreach ($data_drugs as $key => $value)
...
Anyone, anyone, Ferris?

Your $data_drugs is no longer a json, after json_decode is an associative array.
You don't need any loop to see keys and values
$data_drugs = json_decode($json_drugs,true);
print_r($data_drugs);
/* or if you don't like inline */
echo'<pre>';
print_r($data_drugs);
echo'</pre>';
You can use var_dump($data_drugs) - keys and values with types, probably you don't need this
But if you want to display keys and values more ...fancy use a recursive function
function show($x){
foreach($x as $key=>$val){
echo"<p>$key : ";
if(is_array($val)){ echo". . ."; show($val);}
else{ echo"$val</p>";}}}
show($data_drugs);

Related

how to remove duplicate array value from multidimensional associative array?

contains the following i am trying get array_unique value from multidimensional associative array
Here, i am only showing only sample array which is similar to this.
$array = ['games'=>[['vollyball', 'football'], ['vollyball', 'football'], ['rubby', 'chess']]];
Here is tried so for
foreach ($array as $key => &$value) {
$value = array_unique($value);
}
echo "<pre>";
print_r($array);
echo "</pre>";
exit;
Here i am expecting output is,
$array = ['games'=>[['vollyball', 'football'], ['rubby', 'chess']]];
Here the array should be same even after removing duplicate from multidimensional array.
Thanks for your time and suggestions.
you could try the following:
$a=array_values(array_unique(array_merge(...$array['games'])));
This assumes that all your usable values are below $array['games'].
Edit:
Here is another way, using array_walk:
array_walk($array['games'],function($itm){global $res; $res[json_encode($itm)]=$itm;});
echo json_encode(array_values($res));
I don't like the global $res array very much, but this is a way forward, I believe. In the callback function of array_walk() I add all values to an associative array ($res). The keys are JSON representations of their actual values. This way I will overwrite identical values in the associative array $res and will end up with a set of unique values when I apply the array_values() function at the end to turn it back into a non-associative array.
The result is:
[["vollyball","football"],["rubby","chess"]]
Here is a little demo you can check out: http://rextester.com/JEKE60636
2. edit
Using a wrapper function I can now do without the global variable $res and do the operation in-place, i. e. removing duplicate elements directly from the source array:
function unique(&$ag){
array_walk($ag,function($itm,$key) use (&$ag,&$res) {
if (isset($res[json_encode($itm)])) array_splice($ag,$key,1);
else $res[json_encode($itm)]=1.;
});
}
unique($array['games']);
echo json_encode($array)
This will result in
{"games":[["vollyball","football"],["rubby","chess"]]}
see here: http://rextester.com/YZLEK39965

merge array inside foreach loop

I want to merge array result inside foreach loop. Is there any solution about this or other best way. Thanks in advance.
PHP code
include('Config.php');
$data = json_decode(file_get_contents("php://input"));
foreach($data->dataVal as $key => $value){
echo json_encode($config->query($key,$value));}
//this is the response code above --> how to merge this 2,3 array result into one only
[{"name":"Roi"}][{"name":"Tom"}][{"name":"Chad"}]
//result to be expected like this
[{"name":"Roi","name":"Tom","name":"Chad"}] // this is i want
The nearest you will get is by building up an array of the data in the foreach loop and JSON encoding the result...
$result = array();
foreach($data->dataVal as $key => $value){
$result[] = $config->query($key,$value);
}
echo json_encode($result);
This stops having repeated values for the name.
In your original attempt, you were encoding each row separately, so the JSON was invalid.

Multidimensional array - how to get specific values from array

I have converted Excel data into Php array using toArray()..
actually my result is
My question how to get value from this Multidimensional array? and also how to i get header and value from array in separately?
you can access value, by following the path of the array. so in your case :
$yourArrayName['Worksheet'][0][0], will return SNo
Get one value:
print_r($your_array['Worksheet'][0]);
Get values with loop:
foreach ($your_array as $key => $value)
{
echo $key; // 'Worksheet'
print_r $value;
}
If you are trying to extract all the values of specific key then you should use for or foreach or while loop...
its something like
<?php
$array = YOUR ARRAY;
$c=count($array);
for ( $i=0; $i < $c; $i++)
{
echo $array[$i]['StudentName'];
}
?>
else if you want to get a specific value manually You can easily traverse to your value as
$array = YOUR ARRAY
echo $ara['Worksheet'][0]['StudentName']

PHP removing elements from array in a foreach loop

I'm trying to unset() some elements from an array but when using a foreach loop to go through 1 array to delete these elements from another array it does not seems to be working.
if (isset($this->request->post['merge'])) {
$merge_orders = $this->request->post['merge'];
}
$selected_order = min($merge_orders); // Fetch the max value order_id
unset($merge_orders[$selected_order]); // Take it out of the array.
$orders_list = explode(',', $this->request->post['order_id_list']);
$removeKeys = $merge_orders;
foreach($removeKeys as $key) {
unset($orders_list[$key]);
echo $key;
}
echo print_r($orders_list);
The first unset works fine but the second does not, the array is set and properly formatted but it still does not seem to remove the elements from the $orders_list array.
If you only use one parameter on a foreach loop you are delivered the value of the occurance and not the key for the occurance.
Try this so that you are getting a key from the foreach loop and not a value
foreach($removeKeys as $key => $val) {
unset($orders_list[$key]);
echo $key;
}

Merge multiple arrays by index

Im some array that's being returned by some query.. and the result is something like this:
array(array('balance_1'=> '-5', 'balance_2'=>'-21'), array('balance_1'=> '-21', 'balance_2'=>'21'), array('balance_1'=> '-50', 'balance_2'=>'40'))
i want to transform this into an array that looks something like this:
array(array(-5,11,-50), array(-21, 21, 40));
basicly i want to join all balance_1, all balance_2, all balance_3 into separated arrays.
any ideas? thanks
You'll just loop over the list, then collect the values. It's most simple if you reuse the existing keys to group:
foreach ($list as $row) {
foreach ($row as $key=>$value) {
$out[$key][] = $value;
}
}
This way you'll get an $out array, with [balance_1] or [balance_2] holding the value lists.
Loop though the array and use "array_key_exists" if the key exists add to the array, if it doesn't build a new array with your index.
For more can be found here:
http://www.php.net/manual/en/function.array-key-exists.php

Categories