• About

Viet PHP

PHP = ['newbie' => 'cơ bản', 'coder' => 'nâng cao', 'professional'=>'chuyên sâu']

  • PHP
    • OOP
    • Basic
  • WordPress
  • Bài tập PHP
  • PHP 7
Home PHP echo string lồng multidimensional array

echo string lồng multidimensional array

Posted on April 12, 2018 Written by admin Leave a Comment

Tưởng echo mà ngon à, thử gắn với array biết nhau ngay.

Ví dụ có array lồng sau:

// array lồng
$array = array(
array('id' => 1, 'name' => 'cấp 1' , 'parent' => 'cha mẹ index 0'),
array('id' => 2, 'name' => 'cấp 2' , 'parent' => 'cha mẹ 1'),

);

Phân tích thì đây là một array dạng lồng multidimensional.

Thường để lấy hết giá trị array ta dùng hàm foreach, hoặc for. Ví dụ:

foreach ($array as $array) {
echo $array['parent'];
}

Cách đơn giản sau hỗ trợ xuất giá trị nếu xác định được key=> value của array, kể cả array lồng. Ví dụ:

echo $array[0]['name'];
// chú ý index dạng số của array bắt đầu bằng 0 :-)

Câu hỏi là làm sao để echo giá trị của array lồng trong một string.

Câu trả lời là Complex (curly) syntax.

Định nghĩa thần thánh như sau:

This isn’t called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$.

Ta có ví dụ sau:

echo "ví dụ {$array[0]['name']} {$array[0]['parent']}";
// Kết quả: 'ví dụ cấp 1 cha mẹ index 0'

Như vậy dùng cặp ngoặc chéo {} để “bo” biến trong string, biến lúc này là một value lấy từ array lồng.

Noted: Có thể thấy {} bo được biến, element của array và  cả thuộc tính của đối tượng (object property).

Filed Under: Basic, PHP

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • 11 basic PHP questions.
  • How to pass a variable to the callback function provided by Laravel Collection
  • Cài Sodium trên PHP 7.2 Centos
  • Dependency Injection và Container
  • Hàm array_map() và array_walk()

Recent Comments

  • admin on Dependency Injection
  • Vượng on Dependency Injection
  • vượng on Dependency Injection
  • vượng on Dependency Injection
  • vượng on Dependency Injection

Archives

  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018

Categories

  • Bài tập PHP
  • Basic
  • Laravel
  • OOP
  • OOP
  • PHP
  • String
  • Uncategorized
  • WordPress

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Copyright © 2020 · Focus Pro on Genesis Framework · WordPress · Log in