php multi-dimensional array provides three levels of depth instead of two - php

When I execute the code below:
Code:
<?php
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'][] = $jim;
$data['abc'][] = $bob;
print_r($data);
?>
I receive the following output:
Array
(
[abc] => Array
(
[0] => Array
(
[Jim] => 1
)
[1] => Array
(
[Bob] => 1
)
)
)
What I am expecting is the following output:
Array
(
[abc] => Array
(
[Jim] => 1
[Bob] => 1
)
)
How can I achieve this? To rephrase the question, how can I keep it to a single sub-array per a supplied key?

$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'] = array_merge($jim, $bob);
print_r($data);

You are creating array ($data['abc']) which contains an array ([]) of arrays($jim, $bob)
It's the same as writing:
$data['abc'][0] = array('jim' => 1);
$data['abc'][1] = array('bob' => 1);
What you want is probably:
$data['abc'] = array();
$data['abc'] = array_merge($data['abc'], $jim, $bob);

Jim and Bob are array indexes by your own declaration, you have to change them first
<?php
$data = array();
$data['abc']["Jim"] =1;
$data['abc']["Bob"] = 2;
print_r($data);
?>
Demo

Related

Loop through array and separate after

I got an array of links which I am getting from source code. I am looping through the array with a foreach loop and adding the results into a new array.
The problem is: I don't want all the results in one array. But for each link a separate array after I looped over it.
The array I am looping through:
Array
(
[0] => Array
(
[0] => http://videos.volkswagen.nl/videos/videos/
)
[1] => Array
(
[0] => http://videos.volkswagen.nl/videos/service-videos/
)
)
The foreach:
$sourceCats = array();
foreach ($matchesAll as $links) {
$strSourceAll = implode("|",$links);
$source = file_get_contents("$strSourceAll");
htmlspecialchars($source);
$sourceCats[] = $source;
}
How the array sourceCats looks now:
Array
(
[0] => (source code from first link)
[1] => (source code from second link)
)
How I want it to look like:
Array
(
[0] => Array
(
[0] => (source code from first link)
)
[1] => Array
(
[0] => (source code from second link)
)
)
I have tried a few things but nothing worked. Is the idea clear?
Any help will be much appreciated.
<?php
$finalsourceCats = array();
$counter_sourceCats = 0;
$matchesAll = array(
0 => array(
0 => "http://videos.volkswagen.nl/videos/videos/"
),
1 => array(
0 => "http://videos.volkswagen.nl/videos/service-videos/"
)
);
foreach ($matchesAll as $links) {
$sourceCats = 'sourceCats';
$sourceCats = $sourceCats . "_" . $counter_sourceCats;
$sourceCats = array();
$strSourceAll = implode("|", $links);
$source = file_get_contents("$strSourceAll");
htmlspecialchars($source);
$sourceCats[] = $source;
$finalsourceCats[] = $sourceCats;
$counter_sourceCats += 1;
}
echo "<pre>"; print_r($finalsourceCats);

Unique values of a multidimensional array while inside a foreach loop

I am working within a foreach loop and PARTS my code looks like this:
foreach ($query->rows as $row) {
$myarray = explode(",",$row['text']);
print_r($myarray);
}
The Output result of the above is this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Natural Gas
[3] = Combo
)
Array
(
[0] = coal
)
Array
(
[0] = Natural Gas
[1] = Wood
)
Yes I see there are similar questions to this. But none of their answers seem to work for me. I'm thinking it might be because I am working inside an foreach loop. Either way, I was wondering if there was a way to get my output above to look like this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Propane
)
Array
(
[0] = Coal
)
Array
(
[0] = wood
)
All the duplicates gone, without loosing the formatting of this array. Code I have tried.. but "maybe" wrong was:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
EDIT for Sharanya Dutta:
I have alot of other code, but basically this is where Im trying to use it.
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
$output[$row['attribute_id']]['values'][] = $diff; // <--- USE IT HERE
}
Use an array ($arr in the following code) to store the values and print_r only those values which are different from the already stored values:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
}
DEMO
You may even use $diff after the last line in the foreach loop:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
$arr = array_merge($arr, $_arr);
if($diff !== array()) print_r($diff);
}
DEMO
As you iterate the result set rows and explode the text string, filter the individual values in the current row against all values in all previously encountered rows.
If there are any individual values encountered for the first time, then save the unique values of that row as a new row in the result array.
Code: (Demo)
$resultSet = [
['text' => 'Charcoal,Natural Gas,Combo'],
['text' => 'Charcoal,Propane,Combo'],
['text' => 'Charcoal,Propane,Natural Gas,Combo'],
['text' => 'coal'],
['text' => 'Natural Gas,wood'],
];
$result = [];
foreach ($resultSet as $row) {
$clean = array_diff(
explode(',', $row['text']),
...$result
);
if ($clean) {
$result[] = array_values($clean);
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'Charcoal',
1 => 'Natural Gas',
2 => 'Combo',
),
1 =>
array (
0 => 'Propane',
),
2 =>
array (
0 => 'coal',
),
3 =>
array (
0 => 'wood',
),
)

Comparing two arrays with array_diff

I have the following code and am trying to compare two array's with array_diff however I keep getting no results. I not sure if it matters, but there are many fields in the array and I really only want to compare 1 field...is this possible? what am I missing?
<?php
$json = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-AZ&back=7&fmt=json");
$json2 = file_get_contents("http://ebird.org/ws1.1/data/obs/region/recent?rtype=subnational1&r=US-NV&back=7&fmt=json");
$array1 = json_decode($json, TRUE);
$array2 = json_decode($json2, TRUE);
if ( $array1 == $array2 ) {
echo 'There are no differences';
}else
var_dump(array_diff($array2, $array1));
echo 'they are different';
?>
You will need to check the arrays against each other:
$Array_1 = array (1,2,3,4,5);
$Array_2 = array(1,2,3,4,5,6);
print_r(array_diff($Array_1,$Array_2));
Will output:
Array
(
)
Whereas:
print_r(array_diff($Array_2,$Array_1));
will output:
Array
(
[5] => 6
)
So this might be a solution:
function ArrayDiff ($Array_1, $Array_2){
$Compare_1_To_2 = array_diff($Array_1,$Array_2);
$Compare_2_To_1 = array_diff($Array_2,$Array_1);
$Difference_Array = array_merge($Compare_1_To_2,$Compare_2_To_1);
return $Difference_Array;
}
print_r(ArrayDiff($Array_1,$Array_2));
Which will output:
Array
(
[0] => 6
)
Putting this into an if statement:
$Differences = ArrayDiff($Array_2,$Array_1);
if (count($Differences) > 0){
echo 'There Are Differences Between The Array:';
foreach ($Differences AS $Different){
echo "<br>".$Different;
}
All the examples and code is based off the arrays at the start ($Array_1 and $Array_2)
$po_line_array=array();
$po_line_clone_array=array();
foreach($cart->line_items as $line_no => $po_line)
$po_line_array[$line_no]=$po_line->labdip_details_id;
print_r($po_line_array,1);
foreach($cart->line_items_clone as $line_no_clone => $po_line_clone)
$po_line_clone_array[$line_no_clone]=$po_line_clone->labdip_details_id;
print_r($po_line_clone_array,1);
$result=array_diff($po_line_clone_array,$po_line_array);
print_r($result,1);
Output:
Array ( [0] => 101 )
Array ( [0] => 101 [1] => 103 )
Array ( [1] => 103 )

Merge a string in an array

I have this array:
$fields = $_GET['r'];
Which has some ids, for example:
Array (
[0] => 3134
[1] => 3135 )
and then I have this string in $tematiche:
3113,3120
How can I marge this string in the first array? Also, how can I remove the equals id (if any)?
Try,
$fields = array_unique(array_merge($fields,explode(",",$tematiche)));
echo "<pre>";
print_r($fields);
Try this :
$fields = $_GET['r'];
$string = '3113,3120';
$array = explode(",",$string);
$res_array = array_unique(array_merge($fields,$array));
echo "<pre>";
print_r($res_array);
Output :
Array (
[0] => 3134
[1] => 3135
[2] => 3113
[3] => 3120
)
A combination of explode(), array_merge() and array_unique() would be suitable.
// Make $tematiche into an array
$tematiche_array = explode(',', $tematiche);
// Merge the two arrays
$merged_array = array_merge($fields, $tematiche_array);
// Remove all duplicate values in the array
$unique_array = array_unique($merged_array);
Please try like this. This should work for you.
$a = explode(',', '3113,3120');
print_r(array_merge($fields,$a));

Help understanding a php function - the meaning of $array[]; the [] part

private function jsonArray($object)
{
$json = array();
if(isset($object) && !empty($object))
{
foreach($object as $obj)
{
$json[]["name"] = $obj;
}
}
return $json;
}
We are grabbing an object, and if the conditional is met, we iterate over that object.
Then... I'm lost on this reading... :s
What's the meaning of the [] here?
$json[]["name"] = $obj;
Thanks in advance,
MEM
$json[] adds an element at the end of the array (numeric index). It's the same as having the following code:
$array=array();
$i=0;
foreach($something as $somethingElse)
{
$array[]=$somethingElse;
//is equivalent, in some way, to
$array[$i++]=$somethingElse;
}
That's the equivalent to this:
$json[] = array('name' => $obj);
It adds the contents of $obj to a new field in $json and there in the field "name".
Little example:
$arr = array();
$arr[] = "Hello";
$arr[] = "World!";
Then, $arr will contain:
Array (
0 => "Hello",
1 => "World!"
)
Or, as in your example with another array in the field:
$arr = array();
$arr[]["text"] = "Hello";
$arr[]["text"] = "World!";
Becomes
Array (
0 => Array (
"text" => "Hello"
),
1 => Array (
"text" => "World!"
)
)
$json[] automatically creates a new element at the end of the array - here is an example:
$json[]["name"] = "object1";
$json[]["name"] = "object2";
$json[]["name"] = "object3";
$json[]["name"] = "object4";
And here is what it displays:
Array
(
[0] => Array
(
[name] => object1
)
[1] => Array
(
[name] => object2
)
[2] => Array
(
[name] => object3
)
[3] => Array
(
[name] => object4
)
)

Categories