I have 2 json data from nosql. first match if the search word match in $array1, get the item number then put item number into $array2, get the price of custom search require. But my code cause Invalid argument supplied for foreach() in
foreach($json2[$num] as $data2)
$str = 'paper';
$array1 = '[{"a":"1","b":"book"},{"a":"2","b":"paper"}]';
$array2 = '[{"1":["17.00","22.00"]},{"2",["4.50","6.00"]}]';
$json1 = json_decode($array1);
$json2 = json_decode($array2,true);
foreach($json1 as $data1){
if(preg_match('#'.$data1->b.'#',$str,$match)){
$num = $data1->a; // $num = 2
}
}
foreach($json2[$num] as $data2){
foreach($data2 as $newdata){
echo $newdata.'<br />'; // 4.50, 6.00
}
}
First off your JSON for $array2 is not valid. It should be:
[{"1":["17.00","22.00"]},{"2":["4.50","6.00"]}]
-----------------------------^
This should be a ":", not a ","
Your JSON is actually an array of objects (arrays). var_dump($json2); shows this.
array(2) {
[0]=>
array(1) {
[1]=>
array(2) {
[0]=>
string(5) "17.00"
[1]=>
string(5) "22.00"
}
}
[1]=>
array(1) {
[2]=>
array(2) {
[0]=>
string(4) "4.50"
[1]=>
string(4) "6.00"
}
}
}
You're gonna need to loop over it like this:
foreach($json2 as $data2){
if(array_key_exists($num, $data2)){
$data2 = $data2[$num];
foreach($data2 as $newdata){
echo $newdata.'<br />'; // 4.50, 6.00
}
}
}
If $num = 2 in your comments is correct, you'll be accessing the third element in $json2 but you can't since there only are two.
Update
Oops, how did I miss this? Your $array2 already has the indices right there, you're just not loading them properly. You can simply loop through $array2 and look for the key. However, a better solution would be to load the data properly, by filling $array2 as a dictionary rather than a list.
Related
I want if the first number in the string is 2 the output will be 2 array. How to explode as each array from string.
My code
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
$data = explode(',',$str);
$out = array();
for($i=1;$i < count($data)-1;$i++){
$out[]= explode(';',$data[$i]);
}
$i = $out[0][0];
foreach ($out as $key => $value) {
for($a=0;$a < $i; $a++){
echo $value[$a]. "<br/>";
}
}
?>
I get the result 221107-09-201607-09-201608-09-201610-09-201613
But I want this format
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
//format will be split by semicomma ;
$arr1 = Array('2','1','07-09-2016','08-09-2016','1','100.00');
$arr2 = Array('2','1','07-09-2016','10-09-2016','3','450.00');
?>
The php function array_column will come in handy here. Here is short code example that should output what you are looking for.
<?php
//Your original input
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00";
//explode the array into its sub-arrays
$arrs = explode(",", $str);
//remove the first element that sets how many elements are in each array
$numArrs = array_shift($arrs);
//convert strings into those wanted sub-arrays
array_walk($arrs, function(&$val, $key) { $val = explode(';',$val); });
//make the answer we need
$ans = array();
for($i=0; $i<$numArrs; $i++) {
//array_column does all the work that we want, making life easy
$ans[] = array_column($arrs, $i);
}
var_dump($ans);
This process does assume the string is properly formatted for what we are looking for - it will fail horribly if that is not the case.
Use the explode() function! It's really cool.
Here's how I would solve this problem. You will end up with a 2d array with my code. You can access $arr1 with $fourthStep[0] and $arr2 with $fourthStep[1] etc...
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
$fourthStep = array();
//First, let's split that string up into something a little more.. readable.
$firstStep = explode(",",$str);
//$firstStep[0] contains our count for the total array count.
foreach($firstStep as $secondStep){ //Our second step is to loop through the newly created array which splits each section of your array
if ($secondStep != $firstStep[0]){ //skip the first part, as that is only telling us of array count
$thirdStep = explode(";",$secondStep); //third step is to get each data part of each section. The count of this array should be 'firstStep[0]-1'
for($i = 0; $i<$firstStep[0]; $i++){
//Now we want to assign the values into a 2D array
$fourthStep[$i][count($fourthStep[$i])] = $thirdStep[$i];
}
}
}
var_dump($fourthStep);
?>
Result:
array(2) { [0]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "08-09-2016" [4]=> string(1) "1" [5]=> string(6) "100.00" } [1]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "10-09-2016" [4]=> string(1) "3" [5]=> string(6) "450.00" } }
Just for a further note, you don't need the '2' in the first part of your string to work out how many arrays to split it into, as they use 2 different seperators you can work it out quite easily. Save like 8 bits of space or somethin'
I want to get the sum of all the values in array in php. Here I have array
$_SESSION['price'][];
I have some values in the array which has been inserted in to array in each iteration.
when do var_dump($_SESSION['price']); of array I am getting
array(1) { [0]=> string(4) "4806" } array(1) { [0]=> string(5) "65000" } array(1) { [0]=> string(5) "44005" } array(1) { [0]=> string(6) "215668" } array(1) { [0]=> string(4) "7896" }
now I want to calculate each value i.e 4806+ 65000+44005+215668+7896
How can I do this?
I tried echo "totalsum".array_sum($_SESSION['cart_total']);
but I got the output
totalsum4806totalsum65000totalsum44005totalsum215668totalsum7896
You can simply use array_sum like as
echo array_sum(call_user_func_array('array_merge', $arr));
Or for PHP > 5.5.0 You can also use array_column like as
echo array_sum(array_column($arr,0));
Output:
337375
Demo
Apparently you have a 2-dimensional array. Every element of $_SESSION['price'] is an array with one element, rather than a price. I'm not sure why you did it that way, but you'll need to write a loop to access them.
$sum = 0;
foreach ($_SESSION['price'] AS $subarray) {
$sum += $subarray[0];
}
Maybe you should fix whatever is creating the session variable so it makes it a 1-dimensional array. The sub-arrays don't seem to serve any purpose.
Try this: I've manipulated your array
$arr = $_SESSION['price'];
foreach($arr as $key => $val)
{
$newVal[] = $val[0];
}
print_r(array_sum($newVal)); //output is 337375
Normally, you would sum an array like this:
$sum = array_sum($_SESSION['price']);
However, this will not work for you for two reasons:
Your values are not stored as integers, but as strings (hence the " in the var dump). (OK, array_sum might convert it to an integer for you, so perhaps this is not a problem in practice.)
Your values are not stored as elements in the array, but for some reason as single elements in a sub array (hence the array(1) { [0]=> in the var dump).
If there are no reasons to why you would want to have it like that, the easiest solution would be to just fix those two things when the array is created, so instead of a nested array of strings you have a flat array of integers.
If that is not possible for some reason, you can sum it like this:
$sum = 0;
foreach($_SESSION['price'] as $e) {
// Convert the first element of the sub array to integer and add it to the $sum.
$sum += (int)$e[0];
}
I think you use $_SESSION['cart_total'], but you have to use like $_SESSION['price']. When the code is like below
$a = array("price" => array("4806", "65000", "44005", "215668", "7896"));
var_dump($a["price"]);
echo "<br>";
echo "totalsum = " . array_sum($a["price"]);
The output will look like below
array(5) { [0]=> string(4) "4806" [1]=> string(5) "65000" [2]=> string(5) "44005" [3]=> string(6) "215668" [4]=> string(4) "7896" }
totalsum = 337375
OR
$a["price"][] = array("4806");
$a["price"][] = array("65000");
$a["price"][] = array("44005");
$a["price"][] = array("215668");
$a["price"][] = array("7896");
$sum = 0;
foreach ($a["price"] AS $price) {
$total += $price[0];
}
echo $total;
I want to sort whole bunch of keys in an array. The key-value pairs are of a large number and a name. It sorts arrays incorrectly on small numbers and it gets even worse when numbers get too big to be stored as integers. If the integers are too big they are stored as strings in an array. And those strings don't sort at all staying in the same place.
All i want to do is to sort the Key-value pairs from largest to smallest.
I have no idea how to do that since the sorting functions fail completely.
I'll appreciate any help I can get.
Here is my code:
<?php
$encodedNames = $_GET['names']; //names array from a html input encoded with JSON.stringify(nameArray);
$names=json_decode($encodedNames); //decode the names
$namesLegacy = (array) NULL; //array that will store key-value pairs (number=>name)
//for each name gets a large number and assigns it as a key
foreach($names as $name){
$name = trim($name);
array_push($namesLegacy, array(getFameNumber($name)=>$name)) ;
}
echo var_dump($namesLegacy) . "<br />";//dumps the array before it is sorted
krsort($namesLegacy);
echo var_dump($namesLegacy) . "<br />";//dumps the array after its sorted
//simply prints each name in a list format
for ($i = 0; $i < sizeof($namesLegacy); $i++) {
$keys = array_values($namesLegacy[$i]);
echo $i+1 .". ".$keys[0] . "<br/>" ;
}
//gets the large number that will become a key and returns it , as a string ?
function getFameNumber($name)
{
$resultTagId = "resultStats";
$name = str_replace(" ", "+", trim($name));
$url='url that will return the large number';
/*can be tested with google url
$url='http://www.google.com/search?q='.$name.'&ie=utf-8&oe=utf-8&aq=t';*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$dom = new DOMDocument();
#$dom->loadHTML( $data );
$resultsTag = $dom->getElementById($resultTagId)->nodeValue;
$results = preg_replace("/[^0-9]/","",$resultsTag);
return $results;
}
?>
Update:
I have run more examples to test if it will sort all non string values correctly and it turns out that it doesnt. (where previously it has worked now it fails)
I have an array
array(3) { [0]=> array(1) { [1800000000]=> string(6) "Robert" } [1]=> array(1) { [591000000]=> string(6) "albert" } [2]=> array(1) { [1100000000]=> string(4) "Anna" } }
and when i run krsort() on it it returns
array(3) { [2]=> array(1) { [1100000000]=> string(4) "Anna" } [1]=> array(1) { [591000000]=> string(6) "albert" } [0]=> array(1) { [1800000000]=> string(6) "Robert" } }
which is not the correct result correct result is
1800000000,
1100000000,
591000000
I tried to converting those string into floats but it mostly made them come out as negative numbers. So i tried going the other way converting small ints to strings, but the strange thing is that they were already strings. It seems that they are converted to ints when i form a key value pair inside an array.
anybody knows what is going on? am i using krsort incorrectly is the problem still because the numbers are too big?
also I will give an example of how it looks like when i have a really big number in my array
array(1) { [0]=> array(1) { ["4430000000"]=> string(3) "son" } }
notice the "" marks around the number where in previous arrays its not there
Update2:
Ok so i know it has nothing to do with how big the integers are.
I placed this code to test it $results = substr($results, 0, -3);
but i still get incorrect results
array(3) { [2]=> array(1) { [1550]=> string(5) "Reeta" } [1]=> array(1) { [1800000]=> string(6) "Robert" } [0]=> array(1) { [1090000]=> string(4) "Anna" } }
I also reversed keys and values and tried sorting with arsort() with same results
If anyone could explain why strings get converted to ints when they are set as keys in the arrays that would be greatly appreciated as well.
here is a krsort manual.
Try
$key = getFameNumber($name);
array_push($namesLegacy, array("$key"=>$name)) ;
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I am creating an array from several text boxes. I am needing to move the elements in the array to insert into the database. Here is the array:
array(2) { [0]=> string(7) "nameone" [1]=> string(7) "nametwo" }
array(2) { [0]=> string(6) "ageone" [1]=> string(6) "agetwo" }
array(2) { [0]=> string(13) "parentnameone" [1]=> string(13) "parentnametwo" }
array(2) { [0]=> string(14) "parentemailone" [1]=> string(14) "parentemailtwo" }
array(2) { [0]=> string(14) "parentphoneone" [1]=> string(14) "parentphonetwo" }
I want to end up with an insert statement such as:
nameone, ageone, parentnameone, parentemailone, parentphoneone
and next row to insert would be
nametwo, agetwo, parentnametwo, parentemailtwo, parentphonetwo
I have tried to create an array with multiple for each loops but I end up with an array that i need to move the keys which brings be back to my original problem.
Is there a method to this madnaess?
Well, lets say your main array contains 5 arrays with 2 elements each. Lets call that $mainArr. "2" in the first line is no. of elements in each subarray. or if the subarraays are not of equal lengths, then the its the length of the largest subarray.
for($i=0;$i<2;$i++) {
foreach($mainArr as $key => $a) {
$ins[$i][] = $a[$i];
} // form an array with insert elements
}
// traverse that to form inserts
foreach($ins as $key => $arr) {
$statements[] = implode(",", $ins[$key]);
}
echo '<pre>';
print_r($statements);
I think thats what you want. If not, let me know. Hope that helps!
$l = count($array[0]);
for ($i=0; $i<$l; $i++) {
// access values like this:
$name = $array[0][$i]; // equals nameone first time and nametwo second time
$age = $array[1][$i];
$parentname = $array[2][$i];
$parentemail = $array[3][$i];
$parentphone = $array[3][$i];
// insert into DB here
}
#!/usr/bin/php
<?php
$val = array('name', 'age', 'parentname', 'parentemail');
$key = array('one', 'two', 'three', 'four', 'five');
$valone = array();
foreach ($val as $k)
array_push($valone, $k.$key[0]);
var_dump($valone);
?>
Outputs :
array(4) {
[0]=>
string(7) "nameone"
[1]=>
string(6) "ageone"
[2]=>
string(13) "parentnameone"
[3]=>
string(14) "parentemailone"
}
Is this what you want you to do ?
I've got two arrays, for which var_dump give the following values:
$array1:
Artifacts:array(2) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } [1]=> array(3) { [0]=> string(7) "module2" [1]=> string(17) "path/to/file2.txt" [2]=> string(0) "" } }
$array2:
Artifacts:array(1) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } }
I would think that doing array_diff($array1,$array2) would give me an array countaining only the second elements. Instead I got an empty array. I try switching the parameters, and still an empty_array, but this time without surprise. Wouldn't array_diff work on arrays of arrays?
From the documentation:
Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
echo (string) array(); gives you just Array, so for array_diff, your arrays look like:
$array1 = array('Array', 'Array');
$array2 = array('Array');
So to create a diff for your arrays, you would need something like this (assuming that every element in the arrays is itself an array):
$diff = array();
foreach($array1 as $val1) {
$contained = false;
foreach($array2 as $val2) {
if(count(array_diff($val1, $val2)) == 0) {
$contained = true;
break;
}
}
if(!$contained) {
$diff[] = $val1;
}
}
Disclaimer: This is more or less just a sketch.
From the array_diff documentation.
This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);
From the array_diff manual page: "This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);."
Asked and answered here:
recursive array_diff()?