Why is the output from my array printing array? - php

I am using the results from a db query to populate an array. If I do a var_dump on the array, it looks fine. However, if I try to access the elements of the array by echoing $myArray[0] or any other element in the array, all I get is array.
Here is an excerpt of my code.
$losers = array();
if ($result=mysqli_store_result($con))
{
while ($row=mysqli_fetch_row($result))
{
//printf("%s\n",$row['Winner']);
if($row[0]!= "MLB"){
$data[] = $row;
echo $row[0] . '<br />';
Where I am using the echo for the row element, no problems, it does fine. Here are the results of my var_dump
array(4) { [0] => array(4) { [0] => string(3) "MLB" [1] => string(15) "Cincinnati Reds" [2] => string(4) "-137" [3] => string(88) "images/mlb/cred.jpg" } [1] => array(4) { [0] => string(3) "MLB" [1] => string(15) "Minnesota Twins" [2] => string(4) "-128" [3] => string(88) "images/mlb/mtwi.jpg" } [2] => array(4) { [0] => string(3) "MLB" [1] => string(14) "Atlanta Braves" [2] => string(4) "-101" [3] => string(88) "images/mlb/Abra.jpg" } [3] => array(4) { [0] => string(3) "MLB" [1] => string(20) "Washington Nationals" [2] => string(4) "-140" [3] => string(88) "images/mlb/wnat.jpg" } }
And this is what happens when I use echo to show the results of the array.
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArray

That is obviously because element 0 is actually an array. When you try to echo an array, not surprisingly, you get Array and a warning. To print an array use print_r($array, true);
$losers = array();
if ($result=mysqli_store_result($con))
{
while ($row=mysqli_fetch_row($result))
{
//printf("%s\n",$row['Winner']);
if($row[0]!= "MLB"){
$data[] = $row;
echo print_r($row[0], true) . '<br />';

Related

PHP Multidimensional array - Remove part duplicates and add up

I have a multidimensional array like so:
array(4) {
[0] => array(2) {
[0] => string(15)
"One"
[1] => string(5)
"11:31"
}
[1] => array(2) {
[0] => string(4)
"Two"
[1] => string(5)
"11:31"
}
[2] => array(2) {
[0] => string(15)
"Three"
[1] => string(5)
"11:31"
}
[3] => array(2) {
[0] => string(4)
"One"
[1] => string(5)
"11:31"
}
}
I am trying to get the ones with the first value removed but added up together. So it would end up like so:
array(3) {
[0] => array(2) {
[0] => string(15)
"One"
[1] => string(5)
"22:62"
}
[1] => array(2) {
[0] => string(4)
"Two"
[1] => string(5)
"11:31"
}
[2] => array(2) {
[0] => string(15)
"Three"
[1] => string(5)
"11:31"
}
}
Note the last 'One' has been removed and the second value in the array has been added up there from two 11:31's to 22:62. I hope that makes sense.
Is there something or a specific function I should look at to push me in the right direction? Any help much appreciated.
This is not just a straight up removing duplicates from what I can tell, as none are ever exactly the same although the second values are in this example, they won't be in live data.
You could make a loop and group elements into a new array using key [0]. It the key doesn't exists in the new array, simply add the new array. Otherwise, you could parse the existing value to add the new value:
$array = [
["One", "11:31"],
["Two", "11:31"],
["Three", "11:31"],
["One", "11:31"],
];
$out = [];
foreach ($array as $item) {
// if $item[0] is not an existing key,
if (!isset($out[$item[0]])) {
// add $item as-is
$out[$item[0]] = $item;
} else {
// parse current time
list($h1, $m1) = explode(':', $item[1]);
$m1 += $h1 * 60;
// parse existing time
list($h2, $m2) = explode(':', $out[$item[0]][1]);
$m1 += $m2 + $h2 * 60;
// compute new time
$h = floor($m1 / 60);
$out[$item[0]][1] = sprintf("%02d:%02d", $h, $m1-$h*60);
}
}
// array_values removes 'named' keys.
print_r(array_values($out));
Output (condensed):
Array
(
[0] => Array ([0] => One [1] => 23:02)
[1] => Array ([0] => Two [1] => 11:31)
[2] => Array ([0] => Three [1] => 11:31)
)

Changing \n into ARRAY values within another ARRAY

I have this ARRAY sent from a FORM
Array
(
[0] => one
two
three
[1] => hello
how
are
)
Since the values are sent via textarea from a form, it has line breakers, so I want to make change every into a array field like so:
Array
(
[0] => Array
(
[0] => one
[1] => two
[2] => three
)
[1] => Array
(
[0] => hello
[1] => how
[2] => are
)
)
This is what I have so far:
foreach ($array as &$valor) {
foreach(preg_split("/((\r?\n)|(\r\n?))/", $valor) as $line){
$arraynew[] = $line;
}
}
But I get this result
Array
(
[0] => one
[1] => two
[2] => three
[3] => hello
[4] => how
[5] => are
)
What am I doing wrong? :(
For each key in the POST array, pop a value onto the final array, with it's values containing an array whoses values represent each line in value of the POST array.
<?php
$data = array(
0 => "one\ntwo\nthree",
1 => "hello\nhow\nare"
);
$final = array();
for($i = 0; $i < count($data); $i++) {
$row = preg_split('/\n/', $data[$i]);
if(is_array($row)) {
for($j = 0; $j < count($row); $j++) {
$final[$i][] = $row[$j];
}
}
}
var_dump($final);
array(2) {
[0] =>
array(3) {
[0] =>
string(3) "one"
[1] =>
string(3) "two"
[2] =>
string(5) "three"
}
[1] =>
array(3) {
[0] =>
string(5) "hello"
[1] =>
string(3) "how"
[2] =>
string(3) "are"
}
}
DEMO
Well, you're really working too hard.
array_map(function($e) { return explode("\n", $e); }, $orig_array);
is all you need. You could use preg_split if you really want, but explode is enough.
You can simply do this
$array=array("one\ntwo\nthree","hello\nhow\nare");
$arraynew=array();
foreach ($array as &$valor) {
$arraynewtemp=array();
foreach(preg_split("/((\r?\n)|(\r\n?))/", $valor) as $line){
$arraynewtemp[] = $line;
}
array_push($arraynew,$arraynewtemp);
}
var_dump($arraynew);
Will output
array(2) {
[0]=>
array(3) {
[0]=>
string(3) "one"
[1]=>
string(3) "two"
[2]=>
string(5) "three"
}
[1]=>
array(3) {
[0]=>
string(5) "hello"
[1]=>
string(3) "how"
[2]=>
string(3) "are"
}
}
This should works

How to get rid of duplicate values from multidimensional array

I want to remove duplicate values from multi-dim array, I tried all the possible solutions which is already described but for me, is not working, can anyone please correct it?
Here's my Array:
Array (
[0] => Array (
[0] => element_10
[1] => block_1
[2] => element_4
[3] => element_1
[4] => element_3
)
[1] => Array (
[0] => block_1
[1] => block_2
[2] => element_8
[3] => element_10
[4] => element_12
[5] => element_14
[6] => element_4
[7] => element_2
[8] => element_3
[9] => element_9
[10] => element_13
[11] => element_7
)
)
Where I want the array in this format:
Array (
[0] => Array (
[0] => element_10
[1] => block_1
[2] => element_4
[3] => element_1
[4] => element_3
)
[1] => Array (
[1] => block_2
[2] => element_8
[4] => element_12
[5] => element_14
[7] => element_2
[9] => element_9
[10] => element_13
[11] => element_7
)
)
Ican setup the key indexes later.
I tried:
function multi_unique($array) {
foreach ($array as $k=>$na)
$new[$k] = serialize($na);
$uniq = array_unique($new);
foreach($uniq as $k=>$ser)
$new1[$k] = unserialize($ser);
return ($new1);
}
No Luck, then I tried:
function array_unique_multidimensional($input)
{
$serialized = array_map('serialize', $input);
$unique = array_unique($serialized);
return array_intersect_key($input, $unique);
}
Still same array returning.
I tried this method too:
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value)
{
if ( is_array($value) )
{
$result[$key] = self::super_unique($value);
}
}
return $result;
}
Please help me, I know it's pretty simple I don't know where I'm losing?
Thanks,
You need to iterate over your list of input arrays. For each value in that array, you need to see if you've previously encountered it, so you'll have to keep a super-set of all values across all arrays, which you gradually append to. If a value already exists in the super-set array, you can remove it, otherwise you can append it.
function multi_unique($arrays) {
$all_values = array();
foreach ($arrays as &$array) {
foreach ($array as $index => $value) {
if (in_array($value, $all_values)) {
// We've seen this value previously
unset($array[$index]);
} else {
// First time we've seen this value, let it pass but record it
$all_values[] = $value;
}
}
}
return $arrays;
}
$values = array (
array ( 'element_10', 'block_1', 'element_4', 'element_1', 'element_3',) ,
array ( 'block_1', 'block_2', 'element_8', 'element_10', 'element_12', 'element_14', 'element_4', 'element_2', 'element_3', 'element_9', 'element_13', 'element_7',)
);
var_dump(multi_unique($values));
Output:
array(2) {
[0]=>
array(5) {
[0]=>
string(10) "element_10"
[1]=>
string(7) "block_1"
[2]=>
string(9) "element_4"
[3]=>
string(9) "element_1"
[4]=>
string(9) "element_3"
}
[1]=>
array(8) {
[1]=>
string(7) "block_2"
[2]=>
string(9) "element_8"
[4]=>
string(10) "element_12"
[5]=>
string(10) "element_14"
[7]=>
string(9) "element_2"
[9]=>
string(9) "element_9"
[10]=>
string(10) "element_13"
[11]=>
string(9) "element_7"
}
}
If you just want to remove duplicates from the second entry of your array, use array_diff():
$array[1] = array_diff($array[1], $array[0]);
Iterate if you want to apply it to an arbitrary length.
Why are you using the serialize function.
Use array_diff instead.
A simple would be.
$orginal = array(array(values), array(values), ...);
$copy = $original;
foreach($original as $k => $subArray) {
$tmpCopy = $copy;
unset($tmpCopy[$k]);
unshift($tmpCopy, $subArray);
$tmpCopy = array_values($tmpCopy);
$original[$k] = call_user_func_array('array_diff', $tmpCopy);
}
This works for a two dimensions array.
Hope it helps.

How to convert the array to string in single array

Below are the result of array
Array
(
[0] => Array
(
[0] => test
[1] => cate
[2] => category
)
)
I want the result to be
$availableTags = ["test","cate","category"];
How to do this in codeigniter php
It's nothing code-igniter specific. The array currently looks like this: [["test","cate","category"]], so just do $availableTags = $originalArray[0];
To copy:
$availableTags = array_slice($originalArray[0],0);
And to stringify:
echo json_encode($availableTags);
$array = $array[0];
Should be enough
$array = [["test","cate","category"]];
var_dump ($array);
$array = $array[0];
var_dump ($array);
Output :
array(1) { [0]=> array(3) { [0]=> string(4) "test" [1]=> string(4) "cate" [2]=> string(8) "category" } }
array(3) { [0]=> string(4) "test" [1]=> string(4) "cate" [2]=> string(8) "category" }
Short and simpler way [A Mix of json_encode and str_replace and explode]
<?php
$data = array('foo',
'baz',
'cow',
'php',
array('bar','dog','xml'));
//Results as string
$stringRes = str_replace(array('[', '"',']'), '' , json_encode($data));
//Results as array
$arrayRes = explode(',', str_replace(array('[', '"',']'), '' , json_encode($data)));
?>
OUTPUT
foo,baz,cow,php,bar,dog,xml
Array ( [0] => foo [1] => baz [2] => cow [3] => php [4] => bar [5] => dog [6] => xml )

Exclude data from brackets using regex (preg_match_all)

Input string:
:txt{sometext}:alpha
I want to extract data like this (extracted from brackets):
Result using preg_match_all():
sometext
Trying like this, but none of this works:
php > preg_match_all('/^(\:txt)(.*)+(\{)(.*)+(\})/i', ':txt{sometext}:alpha', $m); var_dump($m);
array(6) {
[0] =>
array(1) {
[0] =>
string(14) ":txt{sometext}"
}
[1] =>
array(1) {
[0] =>
string(1) ":"
}
[2] =>
array(1) {
[0] =>
string(0) ""
}
[3] =>
array(1) {
[0] =>
string(1) "{"
}
[4] =>
array(1) {
[0] =>
string(0) ""
}
[5] =>
array(1) {
[0] =>
string(1) "}"
}
}
Note: as sample I have like this :txt{sometext}:alpha:another{mydata}, so I can extract data from :another and give results like mydata.
RESULTS:
Result from Sniffer:
php > preg_match_all('/(?<=:txt{)([^}]+)(?=})/', ':txt{sometext}:alpha', $x); var_dump($x);
array(2) {
[0] =>
array(1) {
[0] =>
string(8) "sometext"
}
[1] =>
array(1) {
[0] =>
string(8) "sometext"
}
}
Result from Jerry:
php > preg_match_all('/^:txt\{([^}]+)\}/', ':txt{sometext}:alpha', $x); var_dump($x);
array(2) {
[0] =>
array(1) {
[0] =>
string(14) ":txt{sometext}"
}
[1] =>
array(1) {
[0] =>
string(8) "sometext"
}
}
Why all this, why not just:
(?<=:txt{)([^}]+)(?=})
Regex101 Demo

Categories