PHP: help with array structure - php

My last question helped me get data from a form into an array. The array is fairly different in structure to anything I've used before. I have multiple records with a textbox and checkbox each. Here is the form data:
array(4) {
["product"]=> array(4) {
[0]=> string(5) "Dummy"
[1]=> string(7) "Dummy 2"
[2]=> string(7) "Dummy 3"
[3]=> string(7) "Dummy 4"
}
["tags"]=> array(4) {
[0]=> string(25) "#enter, #product, #hastag"
[1]=> string(0) ""
[2]=> string(25) "#enter, #product, #hastag"
[3]=> string(25) "#enter, #product, #hastag"
}
["chk"]=> array(2) {
[0]=> string(2) "on"
[2]=> string(2) "on"
}
["submit"]=> string(5) "tweet"
}
I want to get the data from this array into a form such as (only if chk = "on"):
tweet[0]["product"] = "dummy"
tweet[0]["tag"] = "hash tag list here"
tweet[1]["product"] = "dummy3"
tweet[1]["tag"] = "hash tag list here"
Any help most appreciated! :)

First I'd recommend using 1 instead of on. You should try to use numerical values whenever possible as they require less processing. I think you need to readjust your HTML, so you don't do any processing on the PHP side at all...
<input type="checkbox" name="tweet[(YOUR_TWEET_ID)][product]" value="PRODUCT_NAME"/>
<input type="text" name="tweet[(YOUR_TWEET_ID)][tags]" value=""/>
This will cause the form to $_POST exactly how you want it without any additional code.
update
foreach ($_POST['tweet'] as $tweetId => $value) {
//again, it'd be a good idea to use a numerical value here
if (strlen($value['product']) > 0) {
//this tweet was checked, lets do with it what we need
//here's how you'd get the tags
echo $_POST['tweet'][$tweetId]['tags'];
}
}

$finalArray = array();
foreach($array['product'] as $key => $name){
if(!empty($array['chk'][$key])){
$finalArray[] = array(
"product" => $name,
"tag" => $array['tags'][$key]);
};
}

Pretty simple:
$i=0;
foreach ($array['chk'] as $key => $val) {
if ($val == "on") {
$new_array[$i]['product'] = $array['product'][$key];
$new_array[$i++]['tags'] = $array['tags'][$key];
}
}
print_r($new_array);
Should do it, there are other ways, this is just one of them.

foreach ($records['chk'] as $id => $temp) {
$tweet[$id]['product'] = $records['product'][$id];
$tweet[$id]['tag'] = $records['tags'][$id];
}

Related

PHP & JSON: How can I get a value from where another value equals xyz?

I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>

Find matching items in array

Absolutely doing my head in here over something that I'm sure is very simple...
I have 2 arrays.
$post_cats which are categories that any given post is in.
$ad_cats which is an array of categories in which ads are placed.
Basically, if a post has in its array of selected categories, a category that matches an item in the array of ad categories, then it must return the matching value/item.
$post_cats returns this
array(4) {
[0]=> array(1) { ["slug"]=> string(6) "energy" }
[1]=> array(1) { ["slug"]=> string(6) "global" }
[2]=> array(1) { ["slug"]=> string(8) "identify" }
[3]=> array(1) { ["slug"]=> string(5) "south" }
}
and $ad_cats returns this
array(6) {
[0]=> array(1) { ["slug"]=> string(5) "north" }
[1]=> array(1) { ["slug"]=> string(5) "south" }
[2]=> array(1) { ["slug"]=> string(4) "east" }
[3]=> array(1) { ["slug"]=> string(4) "west" }
[4]=> array(1) { ["slug"]=> string(6) "global" }
[5]=> array(1) { ["slug"]=> string(8) "fallback" }
}
The duplicated item there is "south", so in my mind the value of array_intersect($post_cats, $ad_cats); should be an array with a single item - "south", correct?
But its returning, what seems like, everything in either of the arrays... I can't for the life of me get it to work..
Using the above example, I need to return "south" to a variable.
So you are looking for items that are in both arrays? ...
What about something like this:
function find_duplicate($array1, $array2)
{
$list = array();
foreach($array1 as $value1)
{
foreach($array2 as $value2)
{
if($value1 == $value2) $list[] = $value1;
}
}
return $list;
}
The best way is to convert those arrays in arrays array_intersect can work with.
Considering:
$a; // first array
$b; // second array
then you would go with:
$a1 = array();
foreach ($a as $v) $a1[] = $v['slug'];
$b1 = array();
foreach ($b as $v) $b1[] = $v['slug'];
$c = array_intersect($a1, $b1);
PHP functions usually work with more powerful algorithms than what you may think; therefore it's a good choice to let PHP functions handle this kind of things.
This solution uses array_map to get at the values and takes the intersection of that
function mapper($a)
{
return $a['slug'];
}
$set1 = array_map('mapper', $post_cats);
$set2 = array_map('mapper', $ad_cats);
$result = array_intersect($set1, $set2);
PhpFiddle for testing.

Check for duplicates within multi-di assoc array

I have an array like the one below, I need to check for duplicates within the multi-dimensional associative array. I don't think that I really need to say much more, I've already tried array_unique and it happens to think things are duplicates when they clearly aren't.
I'm looking to change this:
array(3) {
[1]=>
array(2) {
["itself"]=>
string(31) "New York"
["status"]=>
string(18) "great"
}
[2]=>
array(2) {
["itself"]=>
string(36) "New York"
["status"]=>
string(22) "great"
}
[3]=>
array(2) {
["itself"]=>
string(29) "New York"
["status"]=>
string(18) "great"
}
}
In to this:
array(1) {
[1]=>
array(2) {
["itself"]=>
string(31) "New York"
["status"]=>
string(18) "great"
}
}
Is this an actual output, because the string-lengths don't match... Maybe some hidden data (html-tags, non-printable characters, etc.)?
If not: array_unique wants a string representation:
$result = array_intersect_key(
$input,
array_unique(array_map('serialize',$input)));
$array = array(YOUR ARRAY);
foreach ($array as $key1 => $value1){
foreach ($array as $key2 => $value2){
if($array[$key1] == $array[$key2] && $key1 != $key2){
unset($array[$key1]);
}
}
}

How to update a multi-array value?

I have this multidimension array in which I need to update a value. What would be the best way to do so? I tried it with 2 foreach loops but wasn't sure if that was the right approach.
Here is the array in question. I need to update the dollar amount on each sub array (i.e. add 3 to it).
array(6) { ["Ground"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "13.63" }
["3 Day Select"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "25.26" }
["2nd Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "32.43" }
["Next Day Air Saver"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "63.00" }
["Next Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "68.65" }
["Next Day Air Early AM"]=> array(2) { [0]=> string(3) "USD" [1]=> string(6) "103.68" } }
Your foreach loop approach would be correct, unless you expect the data format to change e.g. to have more nested levels. If that were the case, then a recursive function would be best suited.
Also, if the data is expected to remain uniform, you could do this:
foreach( $my_array as $index => $row ){
$my_array[$index][1] += 3;
}
cheers!
foreach ($arr as $k=>$row) {
$arr[$k][1] = floatval($row[1]) + 3;
}
foreach ($array as &$subarray) {
foreach ($subarray as $key=>&$value) {
// do whatever you want with $value
// ...
$value = 'something else'; // example
}
}
Try this:
<?php
foreach($first_array as $first_dem_key)
$first_array[$first_dem_key][1] = $first_array[$first_dem_key][1] + 3;
?>

I have two values in an array when i execute the stored Procedure in php But iam returned wih one array value

$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[$rows['field1']] = $rows['field2'];
}
}
return $arr_tmp;
When I say var_dump($result) it has two values in array. But when I Execute arr_tmp it is returned with one value.
out put of ``var_dump($result)`
["param"]=>
array(4) {
["whcode"]=>
string(5) "001"
["mode"]=>
string(1) "A"
["stock_type"]=>
string(4) "AAA"
["process_name"]=>
string(7) "AAAA"
}
["record"]=>
array(2) {
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
}
}
output of var_dump (arr_tmp)
[1]=>
[0]=>
array(3) {
["Field1"]=>
string(5) "value1"
["Field2"]=>
string(1) "CCC"
["Field3"]=>
string(4) "BCC"
}
Both the array values seems to be same
I have the values overwriting in the array
Very hard to understand and read with the bad formatting, please take care to post it with proper formatting.
I think the answer is this:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1']] = $rows['field2'];
}
}
var_dump($arr_tmp);
That should store both sets of data, you just needed to make it a multi-dimensional array. That is, if that is your question and I did not mis-read it through that garbled text above.
Update
This option is not recommended better to learn how to use arrays, simply posted for an example of usage:
$result = $mysql->callSP('STOREDPE1',$in);
$arr_tmp=array();
$i=0;
foreach ($result['record'] as $rows) {
echo "one value";
if(!empty($rows)){
echo "Two Value";
$arr_tmp[][$rows['field1'] . "_$i"] = $rows['field2'];
}
$i++;
}
var_dump($arr_tmp);

Categories