How i can take first array from array - php

I have an array containing two arrays. When I write var_dump($array):
array(7) {
["Article"]=>
array(1) {
[0]=>
string(8) "39-746У"
}
["Visible"]=>
array(1) {
[0]=>
string(1) "1"
}
}
array(7) {
["Article"]=>
array(1) {
[0]=>
string(6) "12-003"
}
["Visible"]=>
array(1) {
[0]=>
string(1) "1"
}
}
When I write var_dump($array[0]) i get NULL.
I want to change Visible in the second array, but it change in two arrays
Real code:
$sql2="select tblCurrencies.name as name,Price,tblArticleInfo.Name as Name,ArticleID,CategoryID,Article,Visible from tblArticles,tblArticleInfo,tblCurrencies where tblArticleInfo.ArticleID=tblArticles.Id and tblArticles.Id='{$tovar_id}' and tblArticles.currencyID=tblCurrencies.id";
$Array2=query_result_as_rows($sql2,$conn);

You have two different kinds of array here, an associative array, with key-value pairs, and a non-associative array, indexed by number.
Associative array:
$a_array = array(
"Article" => "foo",
"Visible" => " bar",
);
Access data in an associative array:
echo $a_array['Article'];
// prints 'foo'
Iterate through an associative array:
foreach ($a_array as $key => $value) {
echo "$key, $value; ";
}
// prints 'Article, foo; Visible, bar'
//
A numerically-indexed array:
$num_array = ('pip', 'pap', 'pop');
Access items in a numerically-indexed array:
echo $num_array[0] . ", " . $num_array[2];
// prints 'pip, pop'
Iterate through the array:
foreach ($num_array as $num) {
echo "$num! ";
}
// prints "pip! pap! pop! "
You have an associative array with a numerically-indexed array inside it:
$array = array(
'Article' => array( '39-746У' ),
'Visible' => array( '1' )
);
var_dump of $array:
array(2) {
["Article"]=>
array(1) {
[0]=>
string(8) "39-746У"
}
["Visible"]=>
array(1) {
[0]=>
string(1) "1"
}
}
To access data, you need to combine the two methods:
echo $array['Article'][0];
// prints "39-746У"
To iterate through the arrays:
foreach ($array as $key => $value) { // this is the outer associative array
echo "outer array key: $key...\n"; // $value is the inner array
foreach ($value as $v) { // $value is a numerically-indexed array
echo "inner array item: $v\n";
}
}
Output:
outer array key: Article
inner array item: 39-746У
outer array key: Visible
inner array item: 1

Here's a workaround:
$array = array(...);
$array_keys = array_keys($array);
$array_first_key = $array_keys[0];
var_dump($array[$array_first_key]);
also:
var_dump(array_shift($array));
With php 5.4+
array_values($array)[0];

Related

Generate multidimensional array based on given array

I have an array say,
$arr = ["x", "y", "z"];
What I want to achieve is create another array based on given array such as
$arr1["x" =>["y" => ["z"]]] = "some value";
Any idea to achieve this? Thanks in advance.
Edited:
'some value' is just a dummy data. What I'm trying to achieve is the multidimensional structure.
You can recursively build an array, taking and removing the first element of an array on each call :
function buildArray($arr, $someValue)
{
if (count($arr) == 0)
return $someValue;
// the key is the first element of the array,
// removed and returned at the same time using array_shift()
return [ array_shift($arr) => buildArray($arr, $someValue) ];
}
$arr = ["x", "y", "z"];
$arr1 = buildArray($arr, "some value");
var_dump($arr1);
echo "------------------------" . PHP_EOL;
// note that $arr is preserved
var_dump($arr);
This outputs :
array(1) {
["x"]=>
array(1) {
["y"]=>
array(1) {
["z"]=>
string(10) "some value"
}
}
}
------------------------
array(3) {
[0]=>
string(1) "x"
[1]=>
string(1) "y"
[2]=>
string(1) "z"
}
$keys = array('key1', 'key2', 'key3');
$value = 'some value';
$md = array();
$md[$keys[count($keys)-1]] = $value;
for($i=count($keys)-2; $i>-1; $i--)
{
$md[$keys[$i]] = $md;
unset($md[$keys[$i+1]]);
}
print_r($md);
You need to create recursive function:
function rec_arr($ar, $val){
$res = [];
if(is_array($ar) && count($ar)>0){
$tmp = $ar[0]; // catching the first value
unset($ar[0]); // unset first value from given array
sort($ar); // makes indexes as 0,1,...
$res[$tmp] = rec_arr($ar, $val); // recursion
} else {
return $val; // passing value to the last element
}
return $res;
}
Demo
Outputs:
Array
(
[x] => Array
(
[y] => Array
(
[z] => some value
)
)
)

Sum values of array by key in PHP

I need to find array values by key and sum this values if key exists in other array. I tried to different combination but I havent a good idea.
array(2) {
["www.test.pl"]=>
array(3) {
["category"]=>
array(3) {
}
["category2"]=>
array(3) {
}
}
["www.test2.pl"]=>
array(3) {
["category"]=>
array(3) {
}
["category2"]=>
array(3) {
}
["category3"]=>
array(3) {
}
}
}
I need to compare keys -"category", "category2" Of every URL ... and sum values if I have keys in both array of URLs.
I tries to do this in this example
link to compare array code
You can summ values in ne array:
// $arr1 - starting array
$arr2 = [];
foreach ($arr1 as $arr){
foreach ($arr as $arKey => $arVal) {
if (isset($arr2[$arKey])) {
$arr2[$arKey]['clicks'] += $arVal['clicks'];
$arr2[$arKey]['impressions'] += $arVal['impressions'];
$arr2[$arKey]['ctr'] += $arVal['ctr'];
} else {
$arr2[] = [
'clicks' => $arVal['clicks'],
'impressions' => $arVal['impressions'],
'ctr' => $arVal['ctr'],
];
}
}
}
I hope it is what you want to do
Like this:
foreach($array as $key => $value){
if(isset($array2[$key])){
$sum = $array2[$key]+$value;
}
}

Php array get all values that are repeating

I have a Php array that have values of times as array values and timestamps as key array is like this:
array(
144454884=>"12:00am", 145454884=>"12:30am", 144474884=>"1:00am", 144454864=>"1:30am", 143354884=>"1:00am", 144654884=>"1:30am", 1444567584=>"2:00am "
);
Timestamp values in above example are not real I wrote an example they are useless anyway unless your timezone matches mine.
Problem:
I need to get "1:00am" and "1:30am" twice I can get repeating values 1 time as shown in answer here:
php return only duplicated entries from an array
I need both repeating values two times with both keys and values being repeated because I need to eliminate those timestamps from week time on my system because of daylight saving a time is repeating and I don't want to show 1:00am at all I just want to show this time as unavailable.
I am not 100% sure what you wanted but this is what I think you need.
Assuming your input array is called $a
$b = array_flip(array_flip($a));
$c = array_diff_key($a, $b);
$b will contain an array of unique values.
$c will contain the elements that were removed.
Results of $b and $c are as follows:
array(5) {
[144454884] = string(7) "12:00am"
[145454884] = string(7) "12:30am"
[143354884] = string(6) "1:00am"
[144654884] = string(6) "1:30am"
[1444567584] = string(7) "2:00am "
}
array(2) {
[144474884] = string(6) "1:00am"
[144454864] = string(6) "1:30am"
}
This code works :
<?php
$array_new = [];
$array_tmp = [];
$array = array(1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U');
//loop trough all elements in array and for ever element create key
//For "world" key is "world"
//For "World" key is "world"
//For "WORLD" key is "world"
//So all this cases have same key and differenet representation eg. "world" => ["world","World","WORLD"]
foreach($array as $k => $v){
$index = strtolower($v);
$array_tmp[$index][] = $v;
}
//loop trough new array with new keys and if there are more than one element(> 1) for some key, all of his representations put in new array
foreach($array_tmp as $k => $v){
if(count($v) > 1){
foreach($v as $k2 => $v2){
$array_new[] = $v2;
}
}
}
echo '<pre>';
print_r($array_new);
echo '<pre>';
A possible solution keeping the key information (I will assign the intermediate results to their own variables otherwise it can be confusing to read)
$array = array(
143354883 => "1:00am",
144454884 => "12:00am",
145454884 => "12:30am",
144474884 => "1:00am",
144454864 => "1:30am",
143354884 => "1:00am",
144654884 => "1:30am",
1444567584 => "2:00am ",
0 => 4,
1 => 4,
2 => 4,
3 => "Test",
4 => "TEST",
5 => "test "
);
// Used this array_iunique function: http://stackoverflow.com/questions/2276349/case-insensitive-array-unique
function array_iunique($array) {
return array_intersect_key(
$array,
array_unique(array_map("StrToLower",$array))
);
}
$unique = array_iunique($array);
// Then get the difference by key, that will give you all the duplicate values:
$diff_key = array_diff_key($array, $unique);
// Now we have to find the values that are in the $diff_key and the $unique because we also want to have those:
$correspondingValues = array_uintersect($unique, $diff_key, "strcasecmp");
// Then we have to combine the $duplicate values with the $diff_key and preserve the keys:
$result = array_replace($correspondingValues, $diff_key);
var_dump($result);
Will result in:
array(10) {
[143354883]=>
string(6) "1:00am"
[144454864]=>
string(6) "1:30am"
[0]=>
int(4)
[3]=>
string(4) "Test"
[144474884]=>
string(6) "1:00am"
[143354884]=>
string(6) "1:00am"
[144654884]=>
string(6) "1:30am"
[1]=>
int(4)
[2]=>
int(4)
[4]=>
string(4) "TEST"
}

Change indexed Array to Associative Array PHP

I have an array from json_decode. And i want to reformat it.
this is my array format.
["Schedule"]=>array(1) {
["Origin"]=>
string(3) "LAX"
["Destination"]=>
string(2) "CGK"
["DateMarket"]=>
array(2) {
["DepartDate"]=>
string(19) "2015-02-01T00:00:00"
["Journeys"]=>
array(6) {
[0]=>
array(6) {
[0]=>
string(2) "3210"
[1]=>
string(14) "Plane Name"
[2]=>
string(8) "20150201"
[3]=>
string(8) "20150201"
[4]=>
string(4) "0815"
[5]=>
string(4) "1524"
}
}
}
And i want change the indexed array to associative with foreach function.
And here is my PHP code
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value->Name= $value[1];
}
But i got an error "Attempt to assign property of non-object on line xXx..
My Question is, how to insert a new associative array to indexed array like the example that i've provide.
UPDATE : I've tried this solution
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name']=$value[1];
}
But my array format still the same, no error.
In this line:
$value->Name= $value[1];
You expect $value to be both object ($value->Name) and array ($value[1]).
Change it to something like:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$response->Schedule['DateMarket']['Journeys'][$key]['Name'] = $value[1];
}
Or even better, without foreach:
$keys = array(
0 => 'Id',
1 => 'Name',
2 => 'DateStart',
3 => 'DateEnd',
4 => 'HourStart',
5 => 'HourEnd',
);
$values = $response->Schedule['DateMarket']['Journeys'];
$response->Schedule['DateMarket']['Journeys'] = array_combine( $keys , $values );
Array_combine makes an array using keys from one input and alues from the other.
Docs: http://php.net/manual/en/function.array-combine.php
Try this:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name'] = $value[1];
}
You want to create new array index, but try to create new object.
foreach ($response->Schedule['DateMarket']['Journeys'] as $key => $value) {
$value['Name'] = $value[1];
}

Convert array in array to string

I wonder if there's easy way to convert array which is in another array to string and keep it in that array ? The array which is inside array always consists of only 1 key. This is array that I have now:
array(6) {
["miestas"]=>
string(2) "CC"
["checkbox"]=>
array(1) {
[0]=>
string(1) "1"
}
["kiekis"]=>
string(5) "Three"
}
And this is the result what I want to get:
array(6) {
["miestas"]=>
string(2) "CC"
["checkbox"]=>
string(1) "1"
["kiekis"]=>
string(5) "Three"
}
Read this: http://php.net/array
Use this: $array['checkbox'] = $array['checkbox'][0];
You can type cast the value
$data['checkbox'] = (string) $data['checkbox'];
array_replace
$replacement = array('checkbox' => 1);
$outputYouWant = array_replace($yourArray, $replacement);
print_r($outputYouWant);
Loops through the input array and checks if value is an array using is_array function. Pushes value array's value at index zero if an array otherwise pushes value to the result array.
$input = array('miestas' => 'CC', 'checkbox' => array("1"), 'kiekis' => 'Three');
$result = array();
foreach($input as $key=>$value) {
$result[$key] = is_array($value) ? $value[0] : $value;
}
// var_dump($result);

Categories