json string to php array - php

I have this json string as below:
$json = '[{"sessionNo":"1","sessionData":["4","6"]},{"sessionNo":"2","sessionData":["2"]},{"sessionNo":"3"}]';
I want to "translate" it as a PHP array. I tried to do the following but it returns an empty array :
var_dump(json_decode($json))
**UPDATE**
Now I am getting this:
array (size=3)
0 =>
array (size=2)
'sessionNo' => string '1' (length=1)
'sessionData' =>
array (size=2)
0 => string '4' (length=1)
1 => string '6' (length=1)
1 =>
array (size=2)
'sessionNo' => string '2' (length=1)
'sessionData' =>
array (size=1)
0 => string '2' (length=1)
2 =>
array (size=1)
'sessionNo' => string '3' (length=1)
I want to loop through this array so I get for each sessionNo the corresponding SessionData, smth like:
sessionNo SessionData
1 4
1 6
2 2

You can use something like...
$json = '[{"sessionNo":"1","sessionData":["4","6"]},{"sessionNo":"2","sessionData":["2"]},{"sessionNo":"3"}]';
$array = json_decode($json, true);
foreach ( $array as $session ) {
if ( isset ($session['sessionData'])){
foreach ( $session['sessionData'] as $data ) {
echo $session['sessionNo']."-".$data.PHP_EOL;
}
}
}
This is just converting the data and then loop over the arrays in a foreach(), only doing the inner one if there is any sessionData.
This outputs..
1-4
1-6
2-2

Related

Store unique values within foreach loop

Im trying to get value of ids for different values of a foreach loop but im confused how to go about it.
$revenue = array('pseudo1', 'pseudo2');
foreach ($revenue as $value) {
if (!$revenue_type) {
$st = getValueDescription($value);
foreach ($st as $stype) {
$tpe[] = $stype->id;
}
$rev[$value] = $tpe;
}
}
when i dump $rev this is what i get
array (size=1)
0 =>
array (size=3)
'pseudo1' =>
array (size=2)
0 => string '9' (length=1)
1 => string '19' (length=2)
'pseudo2' =>
array (size=4)
0 => string '9' (length=1)
1 => string '19' (length=2)
2 => string '1' (length=1)
3 => string '35' (length=2)
what i actually expect
array (size=1)
0 =>
array (size=3)
'pseudo1' =>
array (size=2)
0 => string '9' (length=1)
1 => string '19' (length=2)
'pseudo2' =>
array (size=4)
2 => string '1' (length=1)
3 => string '35' (length=2)
I need the result of my $rev to contain $value as keys but previous values of $tpe keeps adding up with each iteration, im confused how to achieve this.
Does this solve your problem?
$revenue = array('pseudo1', 'pseudo2');
$uniqueValues = [];
foreach ($revenue as $value) {
if (!$revenue_type) {
$st = getValueDescription($value);
$tpe = [];
foreach ($st as $stype) {
if (!in_array($stype->id, $uniqueValues)) {
$tpe[] = $stype->id;
$uniqueValues[] = $stype->id;
}
}
$rev[$value] = $tpe;
}
}
$uniqueValues holds the IDS you already added to the $rev variable, and the $tpe gets empty after every iteration

Convert array index to custom value?

I have an array $indexedarray
printr($indexedarray) gives something like this
array (size=3)
0 => string 'Homes' (length=5)
1 => string 'Apartments' (length=10)
2 => string 'Villas' (length=6)
I want to change this arrays index also same as value, like
array (size=3)
'Homes' => string 'Homes' (length=5)
'Apartments' => string 'Apartments' (length=10)
'Villas' => string 'Villas' (length=6)
is it posssible??
You can use array_combine:
$indexedarray= ['Homes', 'Apartments', 'Villas'];
print_r(array_combine($indexedarray, $indexedarray));
Gives:
Array
(
[Homes] => Homes
[Apartments] => Apartments
[Villas] => Villas
)
But be aware that your duplicate values will be dropped. Keys will be unique!
Try This :
$myArray = [
0 => 'Homes',
1 => 'Apartments',
2 => 'Villas' ];
$newArray = [];
foreach($myArray as $key => $value){
$newArray[$value] = $value;
}
var_dump($newArray);

Php Convert Multidimensional array to string

Below is my function:
public function getChildrenId(){
$child_id = array($this->db->query("SELECT customer_id
FROM " . DB_PREFIX . "customer
WHERE parent IN ( " .(int)$this->customer->getId().") "));
foreach($child_id as $id =>$value) {
$conv = json_decode(json_encode($value), true);
$final = array_slice($conv,2);
foreach ($final as $gchildren => $key) {
sort($key);
$gr = array_slice($key,0,$this->INF);
}
}
return $gr;
}
It outputs:
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
I am trying to get the values of the nested arrays. When I use foreach I only get data from array[0]. I also tried slicing the parent array and still didn't get it right, it outputs array,array,array.
I would like to extract these arrays values to a new array that I can use to query the database. final_array = array (2,4,7).
Thank you in advance!
If your array looks like this, then the foreach should create the array your looking for.
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
The following php will output array(2,4,7);
<?php
$aNewArray = array();
foreach($aArray as $aArray){
$aNewArray[] = $aArray['customer_id'];
}
var_dump($aNewArray);
?>
You dont need a multidimensional array for this though.

Swap two values in string(s) and sort by second value in php?

I have string like this:
EUR-USD,USD-EUR,SEk-CAD
I want to make this to an array and sort by second currency and I want to the result to be
SEk-CAD,USD-EUR,EUR-USD
(Sorted by CAD, EUR and USD)
This is my attempt and it works, but I'm wondering if I'm not "overdoing" this? Anyone has an easier/better solution to achieve this?
Second currency
Create an array of currency pairs:
array (size=3)
0 =>
array (size=2)
0 => string 'EUR' (length=3)
1 => string 'USD' (length=3)
1 =>
array (size=2)
0 => string 'USD' (length=3)
1 => string 'EUR' (length=3)
2 =>
array (size=2)
0 => string 'SEk' (length=3)
1 => string 'CAD' (length=3)
Reverse order of currencies pairs in above array and put them into a non mutlidimensional array:
array (size=3)
0 => string 'USD-EUR' (length=7)
1 => string 'EUR-USD' (length=7)
2 => string 'CAD-SEk' (length=7)
Sort the array (with sort() ) and glue that array into a new string
string 'CAD-SEk,EUR-USD,USD-EUR' (length=23)
Make an array of currency pairs from the newly created string:
array (size=3)
0 =>
array (size=2)
0 => string 'CAD' (length=3)
1 => string 'SEk' (length=3)
1 =>
array (size=2)
0 => string 'EUR' (length=3)
1 => string 'USD' (length=3)
2 =>
array (size=2)
0 => string 'USD' (length=3)
1 => string 'EUR' (length=3)
Reverse order of currencies pairs in above array and put them into a non mutlidimensional array:
array (size=3)
0 => string 'SEk-CAD' (length=7)
1 => string 'USD-EUR' (length=7)
2 => string 'EUR-USD' (length=7)
Glue the array together into a final string:
string 'SEk-CAD,USD-EUR,EUR-USD' (length=23)
Try this:
$currency_string = "EUR-USD,USD-EUR,SEk-CAD";
$currency_array = explode(",", $currency_string);
function compare($a, $b) {
$a = explode("-", $a);
$b = explode("-", $b);
if ($a[1] === $b[1]){
return 0;
}
return ($a[1] < $b[1]) ? -1 : 1;
}
usort($currency_array, "compare");
$final_currency_string = implode(",", $currency_array);
echo $final_currency_string; // Prints SEk-CAD,USD-EUR,EUR-USD
Hope this helps.

count from several multidimensional arrays

i have foreach, which generate following arrays:
==== array 1 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'daa' (length=3)
2 =>
array
'tag' => string 'daf' (length=3)
3 =>
array
'tag' => string 'daaa' (length=4)
4 =>
array
'tag' => string 'daf' (length=3)
5 =>
array
'tag' => string 'daa' (length=3)
6 =>
array
'tag' => string 'daf' (length=3)
7 =>
array
'tag' => string 'daf' (length=3)
8 =>
array
'tag' => string 'daf' (length=3)
9 =>
array
'tag' => string 'abd' (length=3)
10 =>
array
'tag' => string 'abdaa' (length=5)
11 =>
array
'tag' => string 'abda' (length=4)
==== array 2 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'test1' (length=5)
As output i want to get something like:
array
'daf' => '7'
'daa' => '2'
'daaa' => '1'
'abd' => '1'
'abdaa' => '1'
'abda' => '1'
'test1' => '1'
The value of the new array is the count of the element from all aray generatet from the loop. array_count_values() doesn't work here...any suggestions, how to solve the problem?
Did not notice it was 2 dimensional array.
Here is another code.
var_export(
array_count_values(
call_user_func_array('array_merge', array_merge($array1, $array2))
)
);
Something a bit like this should work:
$result = array();
foreach (array_merge($array1, $array2) as $item) {
$name = $item['tag'];
if (!isset($result[$name])) {
$result[$name] = 0;
}
$result[$name]++;
}
Let's make some use of the Standard PHP Library (SPL).
You can "flatten" an array with an RecursiveArrayIterator and RecursiveIteratorIterator. As a result you get an iterator that visits each leaf of your n-dimensional array and still let's you access the actual key of the element. In the next step concat both RecursiveIteratorIterators with an AppendIterator acting like a single interator that visits each element in all of its inner (appended) iterators.
$ai = new AppendIterator;
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)));
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array2)));
$counters = array();
foreach($ai as $key=>$value) {
if ( 'tag'===$key ) {
// # because I don't care whether this array element exists beforehand or not.
// $value has to be something that can be used as an array key (strings in this case)
#$counters[$value] += 1;
}
}
If you want you can even use a FilterIterator instead of the if('tag'===$key). But imho this doesn't increase the readability/value of the code ;-)

Categories